auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testRouterBasic() throws Exception { Properties props = RouterTestUtils.getProps(); VerifiableProperties verifiableProperties = new VerifiableProperties((props)); MockClusterMap mockClusterMap = new MockClusterMap(); BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); Random random = new Random(); byte[] putUserMetadata = new byte[10]; random.nextBytes(putUserMetadata); byte[] putContent = new byte[100]; random.nextBytes(putContent); ReadableStreamChannel putChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(putContent)); Router router = new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); router.putBlob(putBlobProperties, putUserMetadata, putChannel); router.getBlob("nonExistentblobId"); router.deleteBlob("nonExistentblobId"); router.close(); Future<String> future = router.putBlob(putBlobProperties, putUserMetadata, putChannel); Assert.assertTrue(future.isDone()); }

Target:
public void testRouterBasic() throws Exception { Properties props = getNonBlockingRouterProperties(); VerifiableProperties verifiableProperties = new VerifiableProperties((props)); MockClusterMap mockClusterMap = new MockClusterMap(); Router router = new NonBlockingRouterFactory(verifiableProperties, mockClusterMap, new LoggingNotificationSystem()).getRouter(); BlobProperties putBlobProperties = new BlobProperties(100, "serviceId", "memberId", "contentType", false, Utils.Infinite_Time); Random random = new Random(); byte[] putUserMetadata = new byte[10]; random.nextBytes(putUserMetadata); byte[] putContent = new byte[100]; random.nextBytes(putContent); ReadableStreamChannel putChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(putContent)); router.putBlob(putBlobProperties, putUserMetadata, putChannel); router.getBlob("nonExistentBlobId"); router.getBlobInfo("nonExistentBlobid"); router.deleteBlob("nonExistentBlobId"); router.close(); Future<String> future = router.putBlob(putBlobProperties, putUserMetadata, putChannel); Assert.assertTrue(future.isDone()); RouterException e = (RouterException) ((FutureResult<String>) future).error(); Assert.assertEquals(e.getErrorCode(), RouterErrorCode.RouterClosed); }
Source:
public Sample getBySampleBk(final String sampleBk) { return (Sample) this.getSession().createCriteria(Sample.class, "sample") .add(Restrictions.eq("sampleBusinessKey", sampleBk)).uniqueResult(); }

Target:
public Sample getBySampleBk(final String sampleBk){ Sample sample; try { sample = (Sample) this.getSession().createCriteria(Sample.class, "sample").add(Restrictions.eq("sampleBusinessKey", sampleBk)) .uniqueResult(); } catch (HibernateException he) { throw new MiddlewareException( "Unexpected error in executing getBySampleBk(sampleBusinessKey = " + sampleBk + ") query: " + he.getMessage(), he); } return sample; }
Source:
public void testDefaults() { assertRecordedDefaults(recordDefaults(CacheConfig.class) .setCachingEnabled(false) .setCacheType(null) .setBaseDirectory(null) .setValidationEnabled(false) .setMaxInMemoryCacheSize(new DataSize(2, GIGABYTE))); }

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(CacheConfig.class) .setCachingEnabled(false) .setCacheType(null) .setBaseDirectory(null) .setValidationEnabled(false)); }
Source:
public boolean flush () { boolean success = false; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (!nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); success = true; return success; }

Target:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { success[0] = true; } else { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); return success[0]; }
Source:
public T findOrMakePlaceHolder(String uuid){ T entity = findOne(uuid); if (null == entity){ entity = getUnknownEntity(); entity.setUuid(uuid); createOrUpdate(entity); } return entity; }

Target:
public T findOrMakePlaceHolder(String uuid){ T entity = findOne(uuid); if (null == entity){ entity = makeUnknownEntity(); entity.setUuid(uuid); createOrUpdate(entity); } return entity; }
Source:
protected Iterable<Text> getLines(int page) throws CommandException { if (!this.countIterator.hasNext()) { throw new CommandException(t("Already at end of iterator")); } if (page <= this.lastPage) { throw new CommandException(t("You cannot go backwards in an IterablePagination.")); } else if (page > this.lastPage + 1) { getLines(page - 1); } this.lastPage = page; if (getMaxContentLinesPerPage() <= 0) { return Lists.newArrayList(Iterators.transform(this.countIterator, new Function<Map.Entry<Text, Integer>, Text>() { @Nullable @Override public Text apply(Map.Entry<Text, Integer> input) { return input.getKey(); } })); } List<Text> ret = new ArrayList<>(getMaxContentLinesPerPage()); int addedLines = 0; while (addedLines <= getMaxContentLinesPerPage()) { if (!this.countIterator.hasNext()) { if (page > 1) { padPage(ret, addedLines, false); } break; } if (addedLines + this.countIterator.peek().getValue() > getMaxContentLinesPerPage()) { padPage(ret, addedLines, true); break; } Map.Entry<Text, Integer> ent = this.countIterator.next(); ret.add(ent.getKey()); addedLines += ent.getValue(); } return ret; }

Target:
protected Iterable<Text> getLines(int page) throws CommandException { if (!this.countIterator.hasNext()) { throw new CommandException(t("You're already at the end of the pagination list iterator.")); } if (page < 1) { throw new CommandException(t("Page %s does not exist!", page)); } if (page <= this.lastPage) { throw new CommandException(t("You cannot go to previous pages in an iterable pagination.")); } else if (page > this.lastPage + 1) { getLines(page - 1); } this.lastPage = page; if (getMaxContentLinesPerPage() <= 0) { return Lists.newArrayList(Iterators.transform(this.countIterator, new Function<Map.Entry<Text, Integer>, Text>() { @Nullable @Override public Text apply(Map.Entry<Text, Integer> input) { return input.getKey(); } })); } List<Text> ret = new ArrayList<>(getMaxContentLinesPerPage()); int addedLines = 0; while (addedLines <= getMaxContentLinesPerPage()) { if (!this.countIterator.hasNext()) { if (page > 1) { padPage(ret, addedLines, false); } break; } if (addedLines + this.countIterator.peek().getValue() > getMaxContentLinesPerPage()) { padPage(ret, addedLines, true); break; } Map.Entry<Text, Integer> ent = this.countIterator.next(); ret.add(ent.getKey()); addedLines += ent.getValue(); } return ret; }
Source:
public boolean isAcceptableReplacement(Part part, boolean refit) { if ((part instanceof AmmoBin) && !(part instanceof LargeCraftAmmoBin)) { EquipmentPart eqpart = (EquipmentPart)part; EquipmentType et = eqpart.getType(); return getType().equals(et) && ((AmmoBin)part).getFullShots() == getFullShots(); } return false; }

Target:
public boolean isAcceptableReplacement(Part part, boolean refit) { if ((part instanceof AmmoBin) && !(part instanceof LargeCraftAmmoBin)) { EquipmentPart eqpart = (EquipmentPart)part; EquipmentType et = eqpart.getType(); return getType().equals(et) && (((AmmoBin) part).getFullShots() == getFullShots()); } return false; }
Source:
private int getStartIndexFor(long t) throws TimeRangeException { if (fIntervals.isEmpty()) { return 0; } HTInterval dummy = new HTInterval(Long.MIN_VALUE, t, 0, TmfStateValue.nullValue()); int index = Collections.binarySearch(fIntervals, dummy, NODE_ORDER); return index >= 0 ? index : -index - 1; }

Target:
private int getStartIndexFor(long t) throws TimeRangeException { if (fIntervals.isEmpty()) { return 0; } HTInterval dummy = new HTInterval(Long.MIN_VALUE, t, 0, TmfStateValue.nullValue()); int index = Collections.binarySearch(fIntervals, dummy, NODE_ORDER); return (index >= 0 ? index : -index - 1); }
Source:
private Long queryResultToLong(QueryResult result) throws KeenQueryClientException { if (result.isLong()) { return result.longValue(); } else { throw new KeenQueryClientException("Count Query Error: expected Long response type."); } }

Target:
private long queryResultToLong(QueryResult result) throws KeenQueryClientException { if (result == null) { throw new NullPointerException("Query Error: expected long response type but received null."); } if (result.isLong()) { return result.longValue(); } else { throw new IllegalStateException("Query Error: expected long response type."); } }
Source:
public BatchExecutionMatcher(BatchExecution expectedBatchExecution) { if (expectedBatchExecution == null) throw new IllegalArgumentException("null expectedBatchExecution"); this.expectedBatchExecution = expectedBatchExecution; }

Target:
BatchExecutionMatcher(BatchExecution expectedBatchExecution) { if (expectedBatchExecution == null) throw new IllegalArgumentException("null expectedBatchExecution"); this.expectedBatchExecution = expectedBatchExecution; }
Source:
public void testWriteNewFile() throws IOException { OutputStream fos = new AtomicFileOutputStream(dstFile); assertFalse(dstFile.exists()); fos.write(TEST_STRING.getBytes()); fos.flush(); assertFalse(dstFile.exists()); fos.close(); assertTrue(dstFile.exists()); String readBackData = FileUtils.readFileToString(dstFile, StandardCharsets.UTF_8); assertEquals(TEST_STRING, readBackData); }

Target:
public void testWriteNewFile() throws IOException { OutputStream fos = new AtomicFileOutputStream(dstFile); assertFalse(dstFile.exists()); fos.write(TEST_STRING.getBytes()); fos.flush(); assertFalse(dstFile.exists()); fos.close(); assertTrue(dstFile.exists()); String readBackData = new String(Files.readAllBytes(dstFile.toPath()), UTF_8); assertEquals(TEST_STRING, readBackData); }
Source:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createConfig(false); final String[] expected = { "19:25: " + getCheckMessage(MSG_FILE_CONTAINS_TAB), }; final File[] files = { new File(getPath("SimpleFileTabCharacterInput.java")), }; verify(createChecker(checkConfig), files, getPath("SimpleFileTabCharacterInput.java"), expected); }

Target:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createConfig(false); final String[] expected = { "19:25: " + getCheckMessage(MSG_FILE_CONTAINS_TAB), }; final File[] files = { new File(getPath("InputFileTabCharacterSimple.java")), }; verify(createChecker(checkConfig), files, getPath("InputFileTabCharacterSimple.java"), expected); }
Source:
public void checkInConnection(ConnectedChannel connectedChannel) { final Timer.Context context = connectionCheckInTime.time(); try { BlockingChannelInfo blockingChannelInfo = connections.get(connectedChannel.getRemoteHost() + connectedChannel.getRemotePort()); if (blockingChannelInfo == null) { logger.error("Unexpected state in connection pool. Host and port not found to checkin connection", connectedChannel.getRemoteHost(), connectedChannel.getRemotePort()); throw new IllegalArgumentException("Connection does not belong to the pool"); } blockingChannelInfo.releaseBlockingChannel((BlockingChannel) connectedChannel); logger.trace("CheckingIn connection for host and port {}", connectedChannel.getRemoteHost(), connectedChannel.getRemotePort()); } finally { context.stop(); } }

Target:
public void checkInConnection(ConnectedChannel connectedChannel) { final Timer.Context context = connectionCheckInTime.time(); try { BlockingChannelInfo blockingChannelInfo = connections.get(connectedChannel.getRemoteHost() + connectedChannel.getRemotePort()); if (blockingChannelInfo == null) { logger.error("Unexpected state in connection pool. Host and port not found to checkin connection", connectedChannel.getRemoteHost(), connectedChannel.getRemotePort()); throw new IllegalArgumentException("Connection does not belong to the pool"); } blockingChannelInfo.releaseBlockingChannel((BlockingChannel) connectedChannel); logger.trace("Checking in connection for host and port {}", connectedChannel.getRemoteHost(), connectedChannel.getRemotePort()); } finally { context.stop(); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); ButterKnife.bind(this); FirebaseAuth.getInstance().signInAnonymously() .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); Toast.makeText(ImageActivity.this, "Authentication failed, uploads and downloads will not work.", Toast.LENGTH_SHORT).show(); } } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); ButterKnife.bind(this); FirebaseAuth.getInstance().signInAnonymously() .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Log.d(TAG, "signInAnonymously:" + task.isSuccessful()); if (!task.isSuccessful()) { Log.w(TAG, "signInAnonymously", task.getException()); Log.w(TAG, getString(R.string.anonymous_auth_failed_msg)); Toast.makeText(ImageActivity.this, getString(R.string.anonymous_auth_failed_toast), Toast.LENGTH_SHORT).show(); } } }); }
Source:
public void matchesDifferentTypes() throws IOException { MatcherAssert.assertThat( new FkContentType( "application/json charset=utf-8", FkContentTypeTest.createTakeWithEmptyResponse() ).route( new RqWithHeader( new RqFake(), FkContentTypeTest.CONTENT_TYPE, "images/*" ) ).has(), Matchers.is(false) ); }

Target:
public void matchesDifferentTypes() throws IOException { MatcherAssert.assertThat( new FkContentType( "application/json charset=utf-8", FkContentTypeTest.emptyResponse() ).route( new RqWithHeader( new RqFake(), FkContentTypeTest.CONTENT_TYPE, "images/*" ) ).has(), Matchers.is(false) ); }
Source:
public static void reset() { injectors.clear(); resourceListeners.clear(); viewListeners.clear(); try { Guice.setAnnotationDatabasePackageNames(null); Guice.setHierarchyTraversalFilterFactory(new HierarchyTraversalFilterFactory()); } catch (AnnotationDatabaseNotFoundException e) { Log.e(RoboGuice.class.getName(), "Unable to clear annotation database.", e); } }

Target:
public static void reset() { injectors.clear(); resourceListeners.clear(); viewListeners.clear(); try { Guice.setAnnotationDatabasePackageNames(null); Guice.setHierarchyTraversalFilterFactory(new HierarchyTraversalFilterFactory()); } catch (AnnotationDatabaseNotFoundException e) { Ln.e(e, "Unable to clear annotation database."); } }
Source:
public void shouldNotSaveTaskWithDuplicateName() { when(tasksDataService.findTasksByName("name")).thenReturn( asList(new Task("name", trigger, asList(action)))); Task t = new Task("name", trigger, asList(action), null, false, false); taskService.save(t); }

Target:
public void shouldNotSaveTaskWithDuplicateName() { when(tasksDataService.findTasksByName("name")).thenReturn( asList(new Task("name", trigger, asList(action)))); Task t = new Task("name", trigger, asList(action), null, false, false); try { taskService.save(t); } finally { verify(tasksDataService, times(1)).findTasksByName(t.getName()); verifyNoMoreInteractions(tasksDataService); } }
Source:
void recognizeNotScheduled() { final Command cmd = requestFactory.createCommand(StringValue.getDefaultInstance()); assertFalse(Commands.isScheduled(cmd)); }

Target:
void recognizeNotScheduled() { Command cmd = requestFactory.createCommand(STR_MSG); assertFalse(Commands.isScheduled(cmd)); }
Source:
private PositionalBufferedStream initIndexablePositionalStream(final File inputFile) { try { final FileInputStream fileStream = new FileInputStream(inputFile); return new PositionalBufferedStream(fileStream); } catch (final FileNotFoundException e) { throw new TribbleException.FeatureFileDoesntExist("Unable to open the input file, most likely the file doesn't exist.", inputFile.getAbsolutePath()); } catch (final IOException e) { throw new TribbleException.MalformedFeatureFile("Error initializing stream", inputFile.getAbsolutePath(), e); } }

Target:
private PositionalBufferedStream initIndexablePositionalStream(final File inputFile) { try { final FileInputStream fileStream = new FileInputStream(inputFile); return new PositionalBufferedStream(fileStream); } catch (final FileNotFoundException e) { throw new TribbleException.FeatureFileDoesntExist("Unable to open the input file, most likely the file doesn't exist.", inputFile.getAbsolutePath()); } }
Source:
private void normalizeMemory(Container container, InternalMachineConfig machineConfig) { long ramLimit = Containers.getRamLimit(container); if (ramLimit == 0) { machineConfig.getAttributes().put(MEMORY_LIMIT_ATTRIBUTE, defaultSidecarMemoryLimitBytes); } String overriddenSidecarMemLimit = wsAttributes.get(format(SIDECAR_MEMORY_LIMIT_ATTR_TEMPLATE, pluginPublisherName)); if (!isNullOrEmpty(overriddenSidecarMemLimit)) { machineConfig .getAttributes() .put( MEMORY_LIMIT_ATTRIBUTE, Long.toString(KubernetesSize.toBytes(overriddenSidecarMemLimit))); } }

Target:
private void normalizeMemory(Container container, InternalMachineConfig machineConfig) { long ramLimit = Containers.getRamLimit(container); if (ramLimit == 0) { machineConfig.getAttributes().put(MEMORY_LIMIT_ATTRIBUTE, defaultSidecarMemoryLimitBytes); } String overriddenSidecarMemLimit = wsAttributes.get(format(SIDECAR_MEMORY_LIMIT_ATTR_TEMPLATE, pluginPublisherAndName)); if (!isNullOrEmpty(overriddenSidecarMemLimit)) { machineConfig .getAttributes() .put( MEMORY_LIMIT_ATTRIBUTE, Long.toString(KubernetesSize.toBytes(overriddenSidecarMemLimit))); } }
Source:
private void runNodeUpdater() throws ExecutionFailedException, MojoExecutionException { Set<File> jarFiles = project.getArtifacts().stream() .filter(artifact -> "jar".equals(artifact.getType())) .map(Artifact::getFile).collect(Collectors.toSet()); File flowResourcesFolder = new File(npmFolder, DEFAULT_FLOW_RESOURCES_FOLDER); final URI nodeDownloadRootURI; try { nodeDownloadRootURI = new URI(nodeDownloadRoot); } catch (URISyntaxException e) { throw new MojoExecutionException("Failed to parse " + nodeDownloadRoot, e); } ClassFinder classFinder = getClassFinder(project); Lookup lookup= createLookup(classFinder); new NodeTasks.Builder(lookup, classFinder, npmFolder, generatedFolder, frontendDirectory) .runNpmInstall(runNpmInstall) .useV14Bootstrap(useDeprecatedV14Bootstrapping()) .enablePackagesUpdate(true) .useByteCodeScanner(optimizeBundle) .withFlowResourcesFolder(flowResourcesFolder) .copyResources(jarFiles) .copyLocalResources(frontendResourcesDirectory) .enableImportsUpdate(true) .withEmbeddableWebComponents( generateEmbeddableWebComponents) .withTokenFile(getTokenFile()).enablePnpm(pnpmEnable) .withConnectApplicationProperties( applicationProperties) .withConnectJavaSourceFolder(javaSourceFolder) .withConnectGeneratedOpenApiJson(openApiJsonFile) .withConnectClientTsApiFolder(generatedTsFolder) .withHomeNodeExecRequired(requireHomeNodeExec) .withNodeVersion(nodeVersion) .withNodeDownloadRoot(nodeDownloadRootURI) .build() .execute(); }

Target:
private void runNodeUpdater() throws ExecutionFailedException, MojoExecutionException { Set<File> jarFiles = project.getArtifacts().stream() .filter(artifact -> "jar".equals(artifact.getType())) .map(Artifact::getFile).collect(Collectors.toSet()); File flowResourcesFolder = new File(npmFolder, DEFAULT_FLOW_RESOURCES_FOLDER); final URI nodeDownloadRootURI; try { nodeDownloadRootURI = new URI(nodeDownloadRoot); } catch (URISyntaxException e) { throw new MojoExecutionException("Failed to parse " + nodeDownloadRoot, e); } ClassFinder classFinder = getClassFinder(project); Lookup lookup= createLookup(classFinder); new NodeTasks.Builder(lookup, npmFolder, generatedFolder, frontendDirectory) .runNpmInstall(runNpmInstall) .useV14Bootstrap(useDeprecatedV14Bootstrapping()) .enablePackagesUpdate(true) .useByteCodeScanner(optimizeBundle) .withFlowResourcesFolder(flowResourcesFolder) .copyResources(jarFiles) .copyLocalResources(frontendResourcesDirectory) .enableImportsUpdate(true) .withEmbeddableWebComponents( generateEmbeddableWebComponents) .withTokenFile(getTokenFile()).enablePnpm(pnpmEnable) .withConnectApplicationProperties( applicationProperties) .withConnectJavaSourceFolder(javaSourceFolder) .withConnectGeneratedOpenApiJson(openApiJsonFile) .withConnectClientTsApiFolder(generatedTsFolder) .withHomeNodeExecRequired(requireHomeNodeExec) .withNodeVersion(nodeVersion) .withNodeDownloadRoot(nodeDownloadRootURI) .build() .execute(); }
Source:
public StorageBlockingStub buildBlockingStub() { return StorageGrpc.newBlockingStub( ComputeEngineChannelBuilder.forAddress(readOptions.getGrpcHostname(), 443) .defaultServiceConfig(getGrpcServiceConfig()) .build()); }

Target:
public StorageBlockingStub buildBlockingStub() { return StorageGrpc.newBlockingStub( ComputeEngineChannelBuilder.forTarget(readOptions.getGrpcServerAddress()) .defaultServiceConfig(getGrpcServiceConfig()) .build()); }
Source:
@Override public void publish(Payload<?, ?, ?, ?> requestPayload, Message originalMessage) { publish(requestPayload, originalMessage, null); }

Target:
public void publish(Payload<?, ?, ?, ?> requestPayload, Message originalMessage) { publish(requestPayload, originalMessage, null); }
Source:
private void configurePropertyValues() { appExtPropertiesFile = Utils.loadProperties(CCM_PROPERTY_FILE_PATH); appExtSecurePropertiesFile = Utils.loadProperties(CCM_SECURE_PROPERTY_FILE_PATH); if(appExtSecurePropertiesFile!=null) { canvasToken = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_CANVAS_ADMIN); canvasURL = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_CANVAS_URL); isStubTesting = Boolean.valueOf( appExtPropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_TEST_STUB)); Utils.canvasToken = canvasToken; Utils.canvasURL = canvasURL; M_log.debug("isStubTesting: " + isStubTesting); } else { M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); } }

Target:
private void configurePropertyValues() { appExtPropertiesFile = Utils.loadProperties(CCM_PROPERTY_FILE_PATH); appExtSecurePropertiesFile = Utils.loadProperties(CCM_SECURE_PROPERTY_FILE_PATH); if(appExtSecurePropertiesFile!=null) { Utils.canvasToken = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_CANVAS_ADMIN); Utils.canvasURL = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_CANVAS_URL); isStubTesting = Boolean.valueOf(appExtPropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_TEST_STUB)); M_log.debug("isStubTesting: " + isStubTesting); } else { M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); } }
Source:
public Boolean loadGestures(String directory) { String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = Utils.makeDirectory(directory); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (Utils.loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; gesturesList.add(f.getName()); } else { totalError += 1; } } else { log.warn("{} is not a file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); return ((totalError == 0) ? true : false); }

Target:
public boolean loadGestures(String directory) { String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = Utils.makeDirectory(directory); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (Utils.loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; gesturesList.add(f.getName()); } else { totalError += 1; } } else { log.warn("{} is not a file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); return ((totalError == 0) ? true : false); }
Source:
public void setReplyAddress(String replyAddress) { synchronized (this) { this.replyAddress = replyAddress; this.evaluatedFastReplyTo = false; } }

Target:
public synchronized void setReplyAddress(String replyAddress) { this.replyAddress = replyAddress; this.evaluatedFastReplyTo = false; }
Source:
public void endWindow() { if (--maxCountOfWindows == 0) { throw new RuntimeException(new InterruptedException("Finished generating data.")); } }

Target:
public void endWindow() { if (--maxCountOfWindows == 0) { throw new ShutdownException(); } }
Source:
public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { String[] qualifiers = NameNormaliser.normaliseName(procName).split( "\\."); String qry = "select 'FUNCTION' as type,btrim(btrim(arguments,'('),')') as param_list,returns from _v_procedure where 1=1"; if (qualifiers.length == 3) { qry += " and lower(database)=? and lower(schema)=? and lower(procedure)=? "; } else if (qualifiers.length == 2) { qry += " and lower(schema)=? and lower(procedure)=? "; } else { qry += " and lower(procedure)=? "; } String type; String paramList; String returns; try (PreparedStatement dc = currentConnection.prepareStatement(qry)) { for (int i = 0; i < qualifiers.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(qualifiers[i])); } ResultSet rs = dc.executeQuery(); if (!rs.next()) { throw new SQLException("Unknown procedure " + procName); } type = rs.getString(1); paramList = rs.getString(2); returns = rs.getString(3); rs.close(); } int position = 0; Direction direction = Direction.INPUT; String paramName; String dataType; String token; Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); if (paramList.length()!=0) { for (String param : paramList.split(",")) { StringTokenizer s = new StringTokenizer(param.trim().toLowerCase(), " ()"); token = s.nextToken(); paramName = "$" + (position + 1); dataType = normaliseTypeName(param); DbParameterAccessor dbp = new DbParameterAccessor(paramName, direction, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } } return allParams; }

Target:
public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { String[] qualifiers = NameNormaliser.normaliseName(procName).split( "\\."); String qry = "select btrim(btrim(arguments,'('),')') as param_list from _v_procedure where 1=1"; if (qualifiers.length == 3) { qry += " and lower(database)=? and lower(schema)=? and lower(procedure)=? "; } else if (qualifiers.length == 2) { qry += " and lower(schema)=? and lower(procedure)=? "; } else { qry += " and lower(procedure)=? "; } String paramList; try (PreparedStatement dc = currentConnection.prepareStatement(qry)) { for (int i = 0; i < qualifiers.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(qualifiers[i])); } ResultSet rs = dc.executeQuery(); if (!rs.next()) { throw new SQLException("Unknown procedure " + procName); } paramList = rs.getString(1); rs.close(); } int position = 0; Direction direction = Direction.INPUT; String paramName; String dataType; String token; Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); if (paramList.length() != 0) { for (String param : paramList.split(",")) { StringTokenizer s = new StringTokenizer(param.trim().toLowerCase(), " ()"); token = s.nextToken(); paramName = "$" + (position + 1); dataType = normaliseTypeName(param); DbParameterAccessor dbp = new DbParameterAccessor(paramName, direction, getSqlType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(paramName), dbp); } } return allParams; }
Source:
public void close(ErrorCondition errorCondition) { if (scheduledPool != null && scheduledPool instanceof ThreadPoolExecutor && scheduledFuture != null && scheduledFuture instanceof RunnableScheduledFuture) { ((ThreadPoolExecutor) scheduledPool).remove((RunnableScheduledFuture)scheduledFuture); } handler.close(errorCondition, this); }

Target:
public void close(ErrorCondition errorCondition) { synchronized (schedulingLock) { isSchedulingCancelled = true; if (scheduledPool != null && scheduledPool instanceof ThreadPoolExecutor && scheduledFuture != null && scheduledFuture instanceof Runnable) { if (!((ThreadPoolExecutor) scheduledPool).remove((Runnable) scheduledFuture)) { log.warn("Scheduled task can't be removed from scheduledPool."); } } } handler.close(errorCondition, this); }
Source:
public BulkResponse executeRequest() { if (bulkRequest.numberOfActions() == 0) { return null; } logger.trace("[{}] ES API CALL: bulk request with actions", jobId, bulkRequest.numberOfActions()); BulkResponse bulkResponse = resultsPersisterService.bulkIndexWithRetry( bulkRequest, jobId, shouldRetry, msg -> auditor.warning(jobId, "Bulk indexing of annotations failed " + msg)); bulkRequest = new BulkRequest(AnnotationIndex.WRITE_ALIAS_NAME); return bulkResponse; }

Target:
public BulkResponse executeRequest() { if (bulkRequest.numberOfActions() == 0) { return null; } logger.trace("[{}] ES API CALL: bulk request with actions", () -> jobId, () -> bulkRequest.numberOfActions()); BulkResponse bulkResponse = resultsPersisterService.bulkIndexWithRetry( bulkRequest, jobId, shouldRetry, msg -> auditor.warning(jobId, "Bulk indexing of annotations failed " + msg)); bulkRequest = new BulkRequest(AnnotationIndex.WRITE_ALIAS_NAME); return bulkResponse; }
Source:
protected SearchQuery setTextFilter(String textField, String queryString){ String sanitizedQueryString; if(isValidEmailAddress(queryString)){ sanitizedQueryString = queryString.toLowerCase().trim(); }else{ sanitizedQueryString = Sanitizer.sanitizeForSearch(queryString).toLowerCase().trim(); } if(!sanitizedQueryString.isEmpty()){ String preparedOrQueryString = prepareOrQueryString(sanitizedQueryString); this.textQueryStrings.add(textField + ":" + preparedOrQueryString); } return this; }

Target:
protected SearchQuery setTextFilter(String textField, String queryString){ String sanitizedQueryString; if(FieldValidator.isValidEmailAddress(queryString)){ sanitizedQueryString = queryString.toLowerCase().trim(); } else { sanitizedQueryString = Sanitizer.sanitizeForSearch(queryString).toLowerCase().trim(); } if(!sanitizedQueryString.isEmpty()){ String preparedOrQueryString = prepareOrQueryString(sanitizedQueryString); this.textQueryStrings.add(textField + ":" + preparedOrQueryString); } return this; }
Source:
public synchronized void runInner() { if (LOGGER.isTraceEnabled()) { LOGGER.trace("sending heartbeat to server"); } sendMessageToMaster(IPCUtils.CONTROL_WORKER_HEARTBEAT).awaitUninterruptibly(); List<ResourceStats> resourceUsage = new ArrayList<ResourceStats>(); collectResourceMeasurements(resourceUsage); sendMessageToMaster(IPCUtils.resourceReport(resourceUsage)).awaitUninterruptibly(); for (ResourceStats stats : resourceUsage) { profilingLogger.recordResource(stats); } }

Target:
public synchronized void runInner() { LOGGER.trace("sending heartbeat to server"); sendMessageToMaster(IPCUtils.CONTROL_WORKER_HEARTBEAT).awaitUninterruptibly(); List<ResourceStats> resourceUsage = new ArrayList<ResourceStats>(); collectResourceMeasurements(resourceUsage); sendMessageToMaster(IPCUtils.resourceReport(resourceUsage)).awaitUninterruptibly(); for (ResourceStats stats : resourceUsage) { try { getProfilingLogger().recordResource(stats); } catch (DbException e) { LOGGER.error("Error flushing profiling logger", e); } } }
Source:
private void parseUpdate(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canUpdate()) { if (isHead(cmd) && !isCommit(cmd)) { return; } validateNewCommits(ctl, cmd); if (cmd.getResult().equals(ReceiveCommand.Result.NOT_ATTEMPTED)) { cmd.execute(rp); } } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { errors.put(Error.CONFIG_UPDATE, GitRepositoryManager.REF_CONFIG); } else { errors.put(Error.UPDATE, ctl.getRefName()); } reject(cmd, "can not update the reference as a fast forward"); } }

Target:
private void parseUpdate(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); if (ctl.canUpdate()) { if (isHead(cmd) && !isCommit(cmd)) { return; } validateNewCommits(ctl, cmd); batch.addCommand(cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { errors.put(Error.CONFIG_UPDATE, GitRepositoryManager.REF_CONFIG); } else { errors.put(Error.UPDATE, ctl.getRefName()); } reject(cmd); } }
Source:
public void resetCursors(final String subscriptionId, final List<NakadiCursor> cursors) throws ServiceUnavailableException, NoSuchSubscriptionException, UnableProcessException, OperationTimeoutException, ZookeeperException, InternalNakadiException, NoSuchEventTypeException, InvalidCursorException { if (cursors.isEmpty()) { throw new UnableProcessException("Cursors are absent"); } final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); validateCursorsBelongToSubscription(subscription, cursors); for (final NakadiCursor cursor : cursors) { cursor.validate(); } final ZkSubscriptionClient zkClient = zkSubscriptionFactory.createClient( subscription, "subscription." + subscriptionId + ".reset_cursors"); final long timeout = TimeUnit.SECONDS.toMillis(nakadiSettings.getDefaultCommitTimeoutSeconds()) + TimeUnit.SECONDS.toMillis(1); zkClient.resetCursors( cursors.stream().map(cursorConverter::convertToNoToken).collect(Collectors.toList()), timeout); }

Target:
public void resetCursors(final String subscriptionId, final List<NakadiCursor> cursors) throws ServiceUnavailableException, NoSuchSubscriptionException, UnableProcessException, OperationTimeoutException, ZookeeperException, InternalNakadiException, NoSuchEventTypeException, InvalidCursorException { final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId); validateCursorsBelongToSubscription(subscription, cursors); for (final NakadiCursor cursor : cursors) { cursor.checkStorageAvailability(); } final Map<TopicRepository, List<NakadiCursor>> topicRepositories = cursors.stream().collect( Collectors.groupingBy( c -> timelineService.getTopicRepository(c.getTimeline()))); for (final Map.Entry<TopicRepository, List<NakadiCursor>> entry: topicRepositories.entrySet()) { entry.getKey().validateReadCursors(entry.getValue()); } final ZkSubscriptionClient zkClient = zkSubscriptionFactory.createClient( subscription, "subscription." + subscriptionId + ".reset_cursors"); final long timeout = TimeUnit.SECONDS.toMillis(nakadiSettings.getDefaultCommitTimeoutSeconds()) + TimeUnit.SECONDS.toMillis(1); zkClient.resetCursors( cursors.stream().map(cursorConverter::convertToNoToken).collect(Collectors.toList()), timeout); }
Source:
private static boolean implementsSerializable(@Nullable Type type) { if (type == null || type.isUnknown()) { return true; } if (type.isPrimitive()) { return true; } if (type.isArray()) { return implementsSerializable(((Type.ArrayType) type).elementType()); } if (type.isClass() || ((JavaType) type).isTagged(JavaType.TYPEVAR)) { return type.erasure().isSubtypeOf("java.io.Serializable"); } return false; }

Target:
private static boolean implementsSerializable(@Nullable Type type) { if (type == null || type.isUnknown() || type.isPrimitive()) { return true; } if (type.isArray()) { return implementsSerializable(((Type.ArrayType) type).elementType()); } if (type.isClass() || ((JavaType) type).isTagged(JavaType.TYPEVAR)) { return type.erasure().isSubtypeOf("java.io.Serializable"); } return false; }
Source:
public void setScanId(int scanId) { this.scanId = scanId; }

Target:
void setScanId(int scanId) { this.scanId = scanId; }
Source:
void initSeek() throws IOException { byte[] rawId = new byte[OBJECT_ID_LENGTH]; match.copyRawTo(rawId, 0); byte[] key = Arrays.copyOf(rawId, objIdLen); BlockReader b = objIndex; do { if (b.seekKey(key) > 0) { blockPos = new LongList(0); return; } long pos = b.readPositionFromIndex(); b = readBlock(pos, objEnd); } while (b.type() == INDEX_BLOCK_TYPE); b.seekKey(key); while (b.next()) { b.parseKey(); if (b.match(key, false)) { blockPos = b.readBlockPositionList(); if (blockPos == null) { initScan(); return; } break; } b.skipValue(); } if (blockPos == null) { blockPos = new LongList(0); } if (blockPos.size() > 0) { long pos = blockPos.get(listIdx++); block = readBlock(pos, scanEnd); } }

Target:
void initSeek() throws IOException { byte[] rawId = new byte[OBJECT_ID_LENGTH]; match.copyRawTo(rawId, 0); byte[] key = Arrays.copyOf(rawId, objIdLen); BlockReader b = objIndex; do { if (b.seekKey(key) > 0) { blockPos = EMPTY_LONG_LIST; return; } long pos = b.readPositionFromIndex(); b = readBlock(pos, objEnd); } while (b.type() == INDEX_BLOCK_TYPE); b.seekKey(key); while (b.next()) { b.parseKey(); if (b.match(key, false)) { blockPos = b.readBlockPositionList(); if (blockPos == null) { initScan(); return; } break; } b.skipValue(); } if (blockPos == null) { blockPos = EMPTY_LONG_LIST; } if (blockPos.size() > 0) { long pos = blockPos.get(listIdx++); block = readBlock(pos, scanEnd); } }
Source:
public CommonFilterDescriptor[] findVisibleFilters(INavigatorContentService contentService, boolean forUI) { List<CommonFilterDescriptor> visibleFilters = new ArrayList<CommonFilterDescriptor>(); CommonFilterDescriptor descriptor; for (Object element : filters.entrySet()) { descriptor = (CommonFilterDescriptor) ((Map.Entry)element).getValue(); if (forUI && !descriptor.isVisibleInUi()) continue; if (contentService.isVisible(descriptor.getId())) { visibleFilters.add(descriptor); } } if (visibleFilters.size() == 0) { return NO_FILTER_DESCRIPTORS; } return visibleFilters .toArray(new CommonFilterDescriptor[visibleFilters.size()]); }

Target:
public CommonFilterDescriptor[] findVisibleFilters(INavigatorContentService contentService, boolean forUI) { List<CommonFilterDescriptor> visibleFilters = new ArrayList<CommonFilterDescriptor>(); for (CommonFilterDescriptor descriptor : filters.values()) { if (forUI && !descriptor.isVisibleInUi()) continue; if (contentService.isVisible(descriptor.getId())) { visibleFilters.add(descriptor); } } if (visibleFilters.size() == 0) { return NO_FILTER_DESCRIPTORS; } return visibleFilters .toArray(new CommonFilterDescriptor[visibleFilters.size()]); }
Source:
public void testSanityCommand(String... args) { SanityTestCommand cmd = new SanityTestCommand(); assertTrue(cmd.apply(bkFlags, args)); }

Target:
public void testSanityCommand(String... args) { SanityTestCommand cmd = new SanityTestCommand(); assertTrue(cmd.apply(bkFlags, args)); try { verifyNew(ClientConfiguration.class, times(1)).withNoArguments(); verify(clientConf, times(1)).addConfiguration(any(Configuration.class)); verify(clientConf, times(1)).setEnsemblePlacementPolicy(LocalBookieEnsemblePlacementPolicy.class); verifyNew(BookKeeper.class).withArguments(clientConf); verify(bk, times(1)).createLedger(1, 1, BookKeeper.DigestType.MAC, new byte[0]); verify(lh, times(6)).getId(); verify(bk, times(1)).openLedger(anyLong(), eq(BookKeeper.DigestType.MAC), eq(new byte[0])); verify(lh, times(1)).getLastAddConfirmed(); verify(bk, times(1)).deleteLedger(anyLong()); verify(bk, times(1)).close(); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } }
Source:
public void testBinaryMinMaxForReusedBackingByteArray() { BinaryStatistics stats = new BinaryStatistics(); byte[] bytes = new byte[] { 10 }; stats.updateStats(Binary.fromReusedByteArray(bytes)); bytes[0] = 20; stats.updateStats(Binary.fromReusedByteArray(bytes)); bytes[0] = 15; stats.updateStats(Binary.fromReusedByteArray(bytes)); assertArrayEquals(new byte[] { 20 }, stats.getMaxBytes()); assertArrayEquals(new byte[] { 10 }, stats.getMinBytes()); }

Target:
public void testBinaryMinMaxForReusedBackingByteArray() { BinaryStatistics stats = new BinaryStatistics(); byte[] bytes = new byte[] { 10 }; final Binary value = Binary.fromReusedByteArray(bytes); stats.updateStats(value); bytes[0] = 20; stats.updateStats(value); bytes[0] = 15; stats.updateStats(value); assertArrayEquals(new byte[] { 20 }, stats.getMaxBytes()); assertArrayEquals(new byte[] { 10 }, stats.getMinBytes()); }
Source:
public StreamOpenAndCloseFactory getStreamOpenAndCloseFactory() { return new StreamOpenAndCloseFactory() { @Override public StreamOpen createStreamOpen(CharSequence to, CharSequence from, String id, String lang) { StreamOpen streamOpen = new StreamOpen(to, from, id, connectionInternal.connection.getConfiguration().getXmlLang(), StreamOpen.StreamContentNamespace.client); return streamOpen; } @Override public StreamClose createStreamClose() { return StreamClose.INSTANCE; } }; }

Target:
public StreamOpenAndCloseFactory getStreamOpenAndCloseFactory() { return new StreamOpenAndCloseFactory() { @Override public StreamOpen createStreamOpen(CharSequence to, CharSequence from, String id, String lang) { String xmlLang = connectionInternal.connection.getConfiguration().getXmlLang(); StreamOpen streamOpen = new StreamOpen(to, from, id, xmlLang, StreamOpen.StreamContentNamespace.client); return streamOpen; } @Override public StreamClose createStreamClose() { return StreamClose.INSTANCE; } }; }
Source:
public void unregisterCriticalComponent(CriticalComponent criticalComponent) { for (CriticalComponentImpl csi : this.criticalServiceList) { if (criticalComponent.equals(csi.getCriticalComponent())) { this.criticalServiceList.remove(csi); logger.debug("Critical service " + criticalComponent.getCriticalComponentName() + " removed, " + System.currentTimeMillis()); } } }

Target:
public void unregisterCriticalComponent(CriticalComponent criticalComponent) { for (CriticalComponentImpl csi : this.criticalComponentList) { if (criticalComponent.equals(csi.getCriticalComponent())) { this.criticalComponentList.remove(csi); logger.debug(new StringBuffer("Critical service ").append(criticalComponent.getCriticalComponentName()) .append(" removed, ").append(System.currentTimeMillis()).toString()); break; } } }
Source:
public boolean apply(final String serverId) { checkNotNull(serverId, "serverId"); logger.trace("looking for state on Server %s", serverId); final Server server = api.getServer(serverId); if (server == null) { throw new IllegalStateException(MessageFormat.format("Server {0} is not found", serverId)); } final VmTools vmTools = server.guest().vmTools(); return vmTools != null && vmTools.runningStatus().equals(VmTools.RunningStatus.RUNNING); }

Target:
public boolean apply(final String serverId) { checkNotNull(serverId, "serverId"); logger.trace("looking for guest tools state on Server %s", serverId); final Server server = api.getServer(serverId); if (server == null) { throw new IllegalStateException(String.format("Server %s is not found", serverId)); } final VmTools vmTools = server.guest().vmTools(); return vmTools != null && vmTools.runningStatus() == VmTools.RunningStatus.RUNNING; }
Source:
public void shouldReportXssInParagraph() throws NullPointerException, IOException { String test = "/shouldReportXssInParagraph/"; this.nano.addHandler(new NanoServerHandler(test) { @Override protected Response serve(IHTTPSession session) { List<String> nameList = session.getParameters().get("name"); String response; if (nameList != null) { response = getHtml("InputInParagraph.html", createResponseMatrix("name",nameList)); } else { response = getHtml("NoInput.html"); } return newFixedLengthResponse(response); } }); HttpMessage msg = this.getHttpMessage(test + "?name=test"); this.rule.init(msg, this.parent); this.rule.scan(); assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getEvidence(), equalTo("</p><script>alert(1);</script><p>")); assertThat(alertsRaised.get(0).getParam(), equalTo("name")); assertThat(alertsRaised.get(0).getAttack(), equalTo("</p><script>alert(1);</script><p>")); assertThat(alertsRaised.get(0).getRisk(), equalTo(Alert.RISK_HIGH)); assertThat(alertsRaised.get(0).getConfidence(), equalTo(Alert.CONFIDENCE_MEDIUM)); }

Target:
public void shouldReportXssInParagraph() throws NullPointerException, IOException { String test = "/shouldReportXssInParagraph/"; this.nano.addHandler(new NanoServerHandler(test) { @Override protected Response serve(IHTTPSession session) { String name = getFirstParamValue(session,"name"); String response; if (name != null) { response = getHtml("InputInParagraph.html", new String[][] {{"name", name}}); } else { response = getHtml("NoInput.html"); } return newFixedLengthResponse(response); } }); HttpMessage msg = this.getHttpMessage(test + "?name=test"); this.rule.init(msg, this.parent); this.rule.scan(); assertThat(alertsRaised.size(), equalTo(1)); assertThat(alertsRaised.get(0).getEvidence(), equalTo("</p><script>alert(1);</script><p>")); assertThat(alertsRaised.get(0).getParam(), equalTo("name")); assertThat(alertsRaised.get(0).getAttack(), equalTo("</p><script>alert(1);</script><p>")); assertThat(alertsRaised.get(0).getRisk(), equalTo(Alert.RISK_HIGH)); assertThat(alertsRaised.get(0).getConfidence(), equalTo(Alert.CONFIDENCE_MEDIUM)); }
Source:
private void setContextParameterIfAbsent(final JBossWebMetaData webMetaData, final String name, final String value) { List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { contextParams = new ArrayList<ParamValueMetaData>(); webMetaData.setContextParams(contextParams); } boolean paramFound = contextParams.stream().anyMatch(param -> name.equals(param.getParamName()) && param.getParamValue() != null); if (! paramFound) { ParamValueMetaData param = new ParamValueMetaData(); param.setParamName(name); param.setParamValue(value); contextParams.add(param); } }

Target:
private void setContextParameterIfAbsent(final JBossWebMetaData webMetaData, final String name, final String value) { List<ParamValueMetaData> contextParams = webMetaData.getContextParams(); if (contextParams == null) { contextParams = new ArrayList<>(); webMetaData.setContextParams(contextParams); } for (ParamValueMetaData param : contextParams) { if (name.equals(param.getParamName()) && param.getParamValue() != null) { return; } } ParamValueMetaData param = new ParamValueMetaData(); param.setParamName(name); param.setParamValue(value); contextParams.add(param); }