auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int percentageSync() { int chainHeadHeight = blockChain.getChainHead().getHeight(); int mostCommonChainHeight; if (peerGroup.getMostCommonChainHeight() > 0) { mostCommonChainHeight = peerGroup.getMostCommonChainHeight(); } else { mostCommonChainHeight = chainHeadHeight; } float percentage = ((float) chainHeadHeight / (float) mostCommonChainHeight) * 100; log.info("mostCommonChainHeight: " + mostCommonChainHeight + "\tchainHeadHeight: " + chainHeadHeight + "\t" + percentage + "%\t" + config.getBestChainHeightEver()); return (int) percentage; }

Target:
private int percentageSync() { int chainHeadHeight = blockChain.getChainHead().getHeight(); int mostCommonChainHeight; if (peerGroup == null) { return 0; } if (peerGroup.getMostCommonChainHeight() > 0) { mostCommonChainHeight = peerGroup.getMostCommonChainHeight(); } else { mostCommonChainHeight = chainHeadHeight; } float percentage = ((float) chainHeadHeight / (float) mostCommonChainHeight) * 100; log.info("mostCommonChainHeight: " + mostCommonChainHeight + "\tchainHeadHeight: " + chainHeadHeight + "\t" + percentage + "%\t" + config.getBestChainHeightEver()); return (int) percentage; }
Source:
private static File getFileFromClassLoaderBeforeLuna(String filename, ClassLoader classLoader) throws IOException { try { Method getClasspathManager = classLoader.getClass().getMethod("getClasspathManager"); if (getClasspathManager != null) { Object classpathManager = getClasspathManager.invoke(classLoader); if (classpathManager != null && classpathManager.getClass() .getName() .equals("org.eclipse.osgi.baseadaptor.loader.ClasspathManager")) { Method getBaseData = classpathManager.getClass().getMethod("getBaseData"); if (getBaseData != null) { Object baseData = getBaseData.invoke(classpathManager, null); if (baseData != null && baseData.getClass().getName().equals("org.eclipse.osgi.baseadaptor.BaseData")) { Method getBundle = baseData.getClass().getMethod("getBundle"); if (getBundle != null) { Object bundle = getBundle.invoke(baseData, null); if (bundle != null && bundle.getClass() .getName() .equals("org.eclipse.osgi.framework.internal.core.BundleHost")) { Method getEntry = bundle.getClass().getMethod("getEntry", String.class); if (getEntry != null) { Object entry = getEntry.invoke(bundle, filename); if (entry != null && entry.getClass().getName().equals("java.net.URL")) { if (entry != null) { URL localURL = FileLocator.toFileURL((URL) entry); return new File(localURL.getFile()); } } } } } } } } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } throw new AssertionFailedError("no file found " + filename); }

Target:
private static File getFileFromClassLoaderBeforeLuna(String filename, ClassLoader classLoader) throws IOException { try { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); if (classpathManager != null) { Object baseData = MethodUtils.invokeExactMethod(classpathManager, "getBaseData", null); if (baseData != null) { Object bundle = MethodUtils.invokeExactMethod(baseData, "getBundle", null); if (bundle != null) { Object entry = MethodUtils.invokeExactMethod(bundle, "getEntry", String.class); if (entry != null) { URL localURL = FileLocator.toFileURL((URL) entry); return new File(localURL.getFile()); } } } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } throw new AssertionFailedError("no file found " + filename); }
Source:
private void rescheduleUnknownWorkflowType(WorkflowInstance instance) { logger.warn("Workflow type not configured to this nFlow instance - rescheduling workflow instance", instance.type); instance = new WorkflowInstance.Builder(instance).setNextActivation(now().plusMinutes(unknownWorkflowTypeRetryDelay)) .setStatus(inProgress).setStateText("Unsupported workflow type").build(); workflowInstanceDao.updateWorkflowInstance(instance, null); logger.debug("Finished."); }

Target:
private void rescheduleUnknownWorkflowType(WorkflowInstance instance) { logger.warn("Workflow type not configured to this nFlow instance - rescheduling workflow instance", instance.type); instance = new WorkflowInstance.Builder(instance).setNextActivation(now().plusMinutes(unknownWorkflowTypeRetryDelay)) .setStatus(inProgress).setStateText("Unsupported workflow type").build(); workflowInstanceDao.updateWorkflowInstance(instance); logger.debug("Finished."); }
Source:
public void write(CorfuPayloadMsg<WriteRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { LogData logData = (LogData) msg.getPayload().getData(); log.debug("log write: type: {}, address: {}, streams: {}", logData.getType(), logData.getToken(), logData.getBackpointerMap()); if (logData.isHole()) { msg.setPriorityLevel(PriorityLevel.HIGH); } batchWriter.addTask(WRITE, msg) .thenRunAsync(() -> { logData.serializeMetadata(); dataCache.put(msg.getPayload().getGlobalAddress(), logData); r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }, executor).exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }

Target:
public void write(CorfuPayloadMsg<WriteRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { LogData logData = (LogData) msg.getPayload().getData(); log.debug("log write: type: {}, address: {}, streams: {}", logData.getType(), logData.getToken(), logData.getBackpointerMap()); if (logData.isHole()) { msg.setPriorityLevel(PriorityLevel.HIGH); } batchWriter.addTask(WRITE, msg) .thenRunAsync(() -> { dataCache.put(msg.getPayload().getGlobalAddress(), logData); r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }, executor).exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
public static FeignClientFactory withMapper(ObjectMapper mapper) { return FeignClientFactory.of( new JAXRSContract(), new JacksonEncoder(mapper), new OptionalAwareDecoder(new TextDelegateDecoder(new JacksonDecoder(mapper)), SerializableErrorErrorDecoder.INSTANCE), SerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient()); }

Target:
public static FeignClientFactory withMapper(ObjectMapper mapper) { return FeignClientFactory.of( new JAXRSContract(), new JacksonEncoder(mapper), new OptionalAwareDecoder(new TextDelegateDecoder(new JacksonDecoder(mapper))), SerializableErrorErrorDecoder.INSTANCE, FeignClientFactory.okHttpClient()); }
Source:
public synchronized String rewrite(Configuration conf, String query) throws GrillException { this.query = query; this.conf = conf; StringBuilder mergedQuery = new StringBuilder(); rewrittenQuery.setLength(0); String queryReplacedUdf = ""; reset(); try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String finalRewrittenQuery = ""; String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { LOG.info("Union Query Part " + i + " : " + queries[i]); ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); reset(); } queryReplacedUdf = replaceUDFForDB(finalRewrittenQuery); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } else { ast = HQLParser.parseHQL(query); buildQuery(); queryReplacedUdf = replaceUDFForDB(rewrittenQuery.toString()); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } } catch (ParseException e) { e.printStackTrace(); } catch (SemanticException e) { e.printStackTrace(); } return queryReplacedUdf; }

Target:
public synchronized String rewrite(Configuration conf, String query) throws GrillException { this.query = query; this.conf = conf; StringBuilder mergedQuery = new StringBuilder(); rewrittenQuery.setLength(0); String queryReplacedUdf = ""; reset(); try { if (query.toLowerCase().matches("(.*)union all(.*)")) { String finalRewrittenQuery = ""; String[] queries = query.toLowerCase().split("union all"); for (int i = 0; i < queries.length; i++) { LOG.info("Union Query Part " + i + " : " + queries[i]); ast = HQLParser.parseHQL(queries[i]); buildQuery(); mergedQuery = rewrittenQuery.append(" union all "); finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all")); reset(); } queryReplacedUdf = replaceUDFForDB(finalRewrittenQuery); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } else { ast = HQLParser.parseHQL(query); buildQuery(); queryReplacedUdf = replaceUDFForDB(rewrittenQuery.toString()); LOG.info("Input Query : " + query); LOG.info("Rewritten Query : " + queryReplacedUdf); } } catch (ParseException e) { throw new GrillException(e); } catch (SemanticException e) { throw new GrillException(e); } catch (HiveException e) { throw new GrillException(e); } return queryReplacedUdf; }
Source:
public void physicallyDeleteSurveyNotEmptySharedModules() { when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of(makeValidMetadata())); Survey survey = createSurvey(); when(mockSurveyDao.getSurvey(any(), eq(false))).thenReturn(survey); service.deleteSurveyPermanently(TEST_STUDY, survey); }

Target:
public void physicallyDeleteSurveyNotEmptySharedModules() { when(mockSharedModuleMetadataService.queryAllMetadata(anyBoolean(), anyBoolean(), anyString(), any(), any(), anyBoolean())).thenReturn(ImmutableList.of(makeValidMetadata())); Survey survey = createSurvey(); when(mockSurveyDao.getSurvey(any(), eq(false))).thenReturn(survey); when(mockSchedulePlanService.getSchedulePlans(ClientInfo.UNKNOWN_CLIENT, TEST_STUDY, true)) .thenReturn(ImmutableList.of()); service.deleteSurveyPermanently(TEST_STUDY, survey); }
Source:
public Optional<InsightCard.Category> generateFutureInsightsByCategory(final Long accountId, final InsightCard.Category category, final DateTime publicationDateLocal) { final Optional<Integer> timeZoneOffsetOptional = sleepStatsDAODynamoDB.getTimeZoneOffset(accountId); if (!timeZoneOffsetOptional.isPresent()) { LOGGER.debug("action=insight-absent insight=correlation_temperature reason=timezoneoffset-absent account_id={}", accountId); return Optional.absent(); } final Integer timeZoneOffset = timeZoneOffsetOptional.get(); final DateTime publicationDateUTC = publicationDateLocal.minusMillis(timeZoneOffset); Optional<InsightCard> insightCardOptional = Optional.absent(); switch (category) { case PARTNER_MOTION: insightCardOptional = PartnerMotionInsight.getInsights(accountId, deviceReadDAO, sleepStatsDAODynamoDB, publicationDateUTC); break; case CORRELATION_TEMP: insightCardOptional = CorrelationTemperature.getInsights(accountId, publicationDateUTC); break; } if (insightCardOptional.isPresent()) { if (marketingInsightPool.contains(category)) { marketingInsightsSeenDAODynamoDB.updateSeenCategories(accountId, category); } LOGGER.info("action=generated_insight_card category={} account_id={} next_action=insert_into_dynamo", insightCardOptional.get(), accountId); this.insightsDAODynamoDB.insertInsight(insightCardOptional.get()); final InsightsLastSeen newInsight = new InsightsLastSeen(accountId, insightCardOptional.get().category, publicationDateUTC); this.insightsLastSeenDAO.markLastSeen(newInsight); return Optional.of(category); } return Optional.absent(); }

Target:
public Optional<InsightCard.Category> generateFutureInsightsByCategory(final Long accountId, final InsightCard.Category category, final DateTime publicationDateLocal) { final Optional<Integer> timeZoneOffsetOptional = sleepStatsDAODynamoDB.getTimeZoneOffset(accountId); if (!timeZoneOffsetOptional.isPresent()) { LOGGER.info("action=insight-absent insight=correlation_temperature reason=timezoneoffset-absent account_id={}", accountId); return Optional.absent(); } final Integer timeZoneOffset = timeZoneOffsetOptional.get(); final DateTime publicationDateUTC = publicationDateLocal.minusMillis(timeZoneOffset); Optional<InsightCard> insightCardOptional = Optional.absent(); switch (category) { case PARTNER_MOTION: insightCardOptional = PartnerMotionInsight.getInsights(accountId, deviceReadDAO, sleepStatsDAODynamoDB, publicationDateUTC); break; case CORRELATION_TEMP: insightCardOptional = CorrelationTemperature.getInsights(accountId, publicationDateUTC); break; } if (insightCardOptional.isPresent()) { if (marketingInsightPool.contains(category)) { marketingInsightsSeenDAODynamoDB.updateSeenCategories(accountId, category); } LOGGER.info("action=generated_insight_card category={} account_id={} next_action=insert_into_dynamo", insightCardOptional.get(), accountId); this.insightsDAODynamoDB.insertInsight(insightCardOptional.get()); final InsightsLastSeen newInsight = new InsightsLastSeen(accountId, insightCardOptional.get().category, publicationDateUTC); this.insightsLastSeenDAO.markLastSeen(newInsight); return Optional.of(category); } return Optional.absent(); }
Source:
public void registerProbe(ProbeDescriptor descriptor) { Class<? extends Probe> probeClass = descriptor.getProbeClass(); Probe probe; try { probe = probeClass.newInstance(); } catch (ReflectiveOperationException e) { throw new ManagementRuntimeException("Cannot create management probe for " + descriptor); } ProbeInfoImpl info = new ProbeInfoImpl(descriptor); infosByTypes.put(probeClass, info); infosByShortcuts.put(descriptor.getShortcut(), info); probesByShortcuts.put(descriptor.getShortcut(), probe); if (probesForHealthCheck.containsKey(descriptor.getShortcut())) { probesForHealthCheck.put(descriptor.getShortcut(), info); } }

Target:
public void registerProbe(ProbeDescriptor descriptor) { Class<? extends Probe> probeClass = descriptor.getProbeClass(); Probe probe; try { probe = probeClass.newInstance(); } catch (ReflectiveOperationException e) { throw new ManagementRuntimeException("Cannot create management probe for " + descriptor); } ProbeInfoImpl info = new ProbeInfoImpl(descriptor); infosByTypes.put(probeClass, info); infosByShortcuts.put(descriptor.getShortcut(), info); probesByShortcuts.put(descriptor.getShortcut(), probe); }
Source:
public String add(Network network) { NetworkForCreate networkForCreate = new NetworkForCreate(); networkForCreate.setAdminStateUp(true); networkForCreate.setName(network.getName()); if (network.getLabel() != null) { networkForCreate.setProviderPhysicalNetwork(network.getLabel()); if (network.getVlanId() == null) { networkForCreate.setProviderNetworkType("flat"); } else { networkForCreate.setProviderNetworkType("vlan"); networkForCreate.setProviderSegmentationId(network.getVlanId()); } } try { org.openstack.quantum.model.Network createdNetwork = getQuantumClient().execute(new CreateNetwork(networkForCreate)); return createdNetwork.getId(); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, new RuntimeException(e)); } }

Target:
public String add(Network network) { NetworkForCreate networkForCreate = new NetworkForCreate(); networkForCreate.setAdminStateUp(true); networkForCreate.setName(network.getName()); if (network.getLabel() != null) { networkForCreate.setProviderPhysicalNetwork(network.getLabel()); if (network.getVlanId() == null) { networkForCreate.setProviderNetworkType("flat"); } else { networkForCreate.setProviderNetworkType("vlan"); networkForCreate.setProviderSegmentationId(network.getVlanId()); } } try { org.openstack.quantum.model.Network createdNetwork = getQuantumClient().networks().create(networkForCreate).execute(); return createdNetwork.getId(); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, new RuntimeException(e)); } }
Source:
public static TextSelection getSelection(IEditorPart editorPart) { Objects.requireNonNull(editorPart, "The given editor part must not be null"); if (!(editorPart instanceof ITextEditor)) { return TextSelection.EMPTY_SELECTION; } ITextEditor textEditor = (ITextEditor) editorPart; ISelectionProvider selectionProvider = textEditor.getSelectionProvider(); if (selectionProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocument document = textEditor.getDocumentProvider().getDocument(editorPart.getEditorInput()); ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); int offset = textSelection.getOffset(); int length = textSelection.getLength(); return calculateSelection(document, offset, length); }

Target:
public static TextSelection getSelection(IEditorPart editorPart) { if (!(editorPart instanceof ITextEditor)) { return TextSelection.EMPTY_SELECTION; } ITextEditor textEditor = (ITextEditor) editorPart; ISelectionProvider selectionProvider = textEditor.getSelectionProvider(); if (selectionProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocumentProvider documentProvider = textEditor.getDocumentProvider(); if (documentProvider == null) { return TextSelection.EMPTY_SELECTION; } IDocument document = documentProvider.getDocument(editorPart.getEditorInput()); if (document == null) { return TextSelection.EMPTY_SELECTION; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); int offset = textSelection.getOffset(); int length = textSelection.getLength(); return calculateSelection(document, offset, length); }
Source:
public static void SetNetworkStatus(Guid vdsGroupId, final Network net) { NetworkStatus status = NetworkStatus.Operational; VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDAO().get(vdsGroupId); network_cluster networkCluster = net.getCluster(); if (networkCluster == null) { networkCluster = DbFacade.getInstance().getNetworkClusterDAO().get(new NetworkClusterId(vdsGroupId, net.getId())); } SearchParameters searchParams = new SearchParameters("hosts: cluster = " + vdsGroup.getname(), SearchType.VDS); searchParams.setMaxCount(Integer.MAX_VALUE); List<VDS> vdsList = (List) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, searchParams).getReturnValue(); if (networkCluster.isRequired()) { for (VDS vds : vdsList) { if (vds.getstatus() != VDSStatus.Up) { continue; } List<VdsNetworkInterface> interfaces = (List<VdsNetworkInterface>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetVdsInterfacesByVdsId, new GetVdsByVdsIdParameters(vds.getId())).getReturnValue(); VdsNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface i) { return StringHelper.EqOp(i.getNetworkName(), net.getname()); } }); if (iface == null) { status = NetworkStatus.NonOperational; break; } } } List<network_cluster> all = DbFacade.getInstance() .getNetworkClusterDAO().getAllForCluster(vdsGroupId); for (network_cluster nc : all) { if (net.getId().equals(nc.getnetwork_id())) { nc.setstatus(status.getValue()); DbFacade.getInstance().getNetworkClusterDAO().updateStatus(nc); break; } } }

Target:
public static void SetNetworkStatus(Guid vdsGroupId, final Network net) { NetworkStatus status = NetworkStatus.Operational; network_cluster networkCluster = DbFacade.getInstance().getNetworkClusterDAO().get(new NetworkClusterId(vdsGroupId, net.getId())); if (networkCluster != null) { VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDAO().get(vdsGroupId); SearchParameters searchParams = new SearchParameters("hosts: cluster = " + vdsGroup.getname(), SearchType.VDS); searchParams.setMaxCount(Integer.MAX_VALUE); List<VDS> vdsList = (List) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, searchParams).getReturnValue(); if (networkCluster.isRequired()) { for (VDS vds : vdsList) { if (vds.getstatus() != VDSStatus.Up) { continue; } List<VdsNetworkInterface> interfaces = (List<VdsNetworkInterface>) Backend .getInstance() .runInternalQuery(VdcQueryType.GetVdsInterfacesByVdsId, new GetVdsByVdsIdParameters(vds.getId())).getReturnValue(); VdsNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface i) { return StringHelper.EqOp(i.getNetworkName(), net.getname()); } }); if (iface == null) { status = NetworkStatus.NonOperational; break; } } } networkCluster.setstatus(status.getValue()); DbFacade.getInstance().getNetworkClusterDAO().updateStatus(networkCluster); } }
Source:
public Map<String, Host> getSpmMap() { return this.spmMap; }

Target:
public ConcurrentHashMap getSpmMap() { return this.spmMap; }
Source:
public int prepare(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { LOG.trace("DummyXAResource.prepare(xid=" + xid + ")"); } return 0; }

Target:
public int prepare(Xid xid) throws XAException { LOG.info("DummyXAResource.prepare(xid=" + xid + ")"); return 0; }
Source:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); DataNodeId dataNodeId = getDataNodeId(); snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }

Target:
public JSONObject getSnapshot() { JSONObject snapshot = new JSONObject(); snapshot.put(REPLICA_NODE, dataNodeId.getHostname() + ":" + dataNodeId.getPort()); snapshot.put(REPLICA_PARTITION, getPartitionId().toPathString()); snapshot.put(REPLICA_PATH, getReplicaPath()); snapshot.put(CAPACITY_BYTES, getCapacityInBytes()); return snapshot; }
Source:
public Long getId() { return boxId; }

Target:
public long getId() { return boxId; }
Source:
public void verifyModeName() { Assertion.assertEquals(MobilePageContent.editModeHeader, getModeName()); PageObjectLogging.log("verifyModeName", "verifying the header shows '" + MobilePageContent.editModeHeader + "'", true); }

Target:
public void verifyModeName() { Assertion.assertEquals(MobilePageContent.editModeHeader, getModeName()); PageObjectLogging.log( "verifyModeName", "The header shows '" + MobilePageContent.editModeHeader + "'", true ); }
Source:
public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); bff.put(value); int val1 = bff.getShort(0); if (val1 < 0) val1 = 65536 + val1; int val2 = bff.getShort(2); if (val2 < 0) val2 = 65536 + val2; return new ObjectLink(val1, val2); }

Target:
public static ObjectLink decodeObjlnk(byte[] value) throws TlvException { ByteBuffer bff = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN); bff.put(value); int val1 = bff.getShort(0) & 0xFFFF; int val2 = bff.getShort(2) & 0xFFFF; return new ObjectLink(val1, val2); }
Source:
public static void main(String[] args) throws IOException, SQLException, InterruptedException { Configuration configuration = new Configuration(args); Set<String> registers = configuration.getRegisters(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool((int) registers.stream().filter(r -> configuration.cloudSearchEndPoint(r).isPresent()).count() + registers.size()); addShutdownHook(executorService); for (String register : registers) { try { DBI dbi = new DBI(configuration.getProperty(register + ".destination.postgres.db.connectionString")); DestinationDBUpdateDAO destinationDBUpdateDAO = createDestinationDBUpdateDAO(dbi); executorService.scheduleAtFixedRate( new IndexerTask(register, createSourceDAO(register, configuration), destinationDBUpdateDAO), 0, 10, TimeUnit.SECONDS ); configuration.cloudSearchEndPoint(register).ifPresent( endPoint -> executorService.scheduleAtFixedRate( new CloudSearchDataUploadTask(register, endPoint, configuration.cloudSearchWaterMarkEndPoint(register).get(), dbi.onDemand(IndexedEntriesUpdateDAO.class)), 0, 10, TimeUnit.SECONDS ) ); } catch (Throwable e) { e.printStackTrace(); ConsoleLogger.log("Error occurred while setting indexer for register: " + register + ". Error is -> " + e.getMessage()); } } Thread.currentThread().join(); }

Target:
public static void main(String[] args) throws IOException, SQLException, InterruptedException { Configuration configuration = new Configuration(args); Set<String> registers = configuration.getRegisters(); ScheduledExecutorService executorService = Executors.newScheduledThreadPool((int) registers.stream().filter(r -> configuration.cloudSearchEndPoint(r).isPresent()).count() + registers.size()); addShutdownHook(executorService); for (String register : registers) { try { DBI dbi = new DBI(configuration.getProperty(register + ".destination.postgres.db.connectionString")); DestinationDBUpdateDAO destinationDBUpdateDAO = createDestinationDBUpdateDAO(dbi); executorService.scheduleAtFixedRate( new IndexerTask(register, createSourceDAO(register, configuration), destinationDBUpdateDAO), 0, 10, TimeUnit.SECONDS ); configuration.cloudSearchEndPoint(register).ifPresent( endPoint -> executorService.scheduleAtFixedRate( new CloudSearchDataUploadTask(register, endPoint, configuration.cloudSearchWaterMarkEndPoint(register).get(), dbi.onDemand(IndexedEntriesUpdateDAO.class)), 0, 5, TimeUnit.MINUTES ) ); } catch (Throwable e) { e.printStackTrace(); ConsoleLogger.log("Error occurred while setting indexer for register: " + register + ". Error is -> " + e.getMessage()); } } Thread.currentThread().join(); }
Source:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo cli : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = cli.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }

Target:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); List<Map<String, String>> parsed = Lists.newArrayList(); Matcher m = LINK_PATTERN.matcher(message); int last = 0; while (m.find()) { addText(parsed, message.substring(last, m.start())); if (m.group(1) != null) { parsed.add(link(m.group(1), m.group(1))); } else if (m.group(2) != null) { if (baseGerritUrl != null) { parsed.add(link(m.group(2), baseGerritUrl + "#/q/" + m.group(2) + ",n,z")); } else { addText(parsed, m.group(2)); } } last = m.end(); } addText(parsed, message.substring(last)); return parsed; }
Source:
public Collection<Bundle> getBundles() { return new ArrayList<>(Arrays.asList( new AssetsBundle("/assets", "/app", "index.html"), new ViewBundle(), new FlywayBundle<T>() { @Override public DataSourceFactory getDataSourceFactory(T configuration) { return configuration.getDataSourceFactory(); } @Override public FlywayFactory getFlywayFactory(T configuration) { return super.getFlywayFactory(configuration); } })); }

Target:
public Iterable<Bundle> getBundles() { return Arrays.asList( new AssetsBundle("/assets", "/app", "index.html"), new ViewBundle(), new FlywayBundle<T>() { @Override public DataSourceFactory getDataSourceFactory(T configuration) { return configuration.getDataSourceFactory(); } @Override public FlywayFactory getFlywayFactory(T configuration) { return super.getFlywayFactory(configuration); } }); }
Source:
private void createUIComponents() { patternHelp = new HyperlinkLabel(""); Icon infoIcon = SonarLintIcons.INFO; patternHelp.setIcon(infoIcon); patternHelp.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent e) { final JLabel label = new JLabel("<<html><body style=\"margin-bottom:1pt\">Configure GLOB patterns to be applied to files in all projects.<br/><br/><b>Examples:</b><br/><table border=\"1\" cellpadding=\"1\" cellspacing=\"0\"><tr><td><pre>** *{!.java}</pre></td><td>Exclude everything except Java files</td></tr></table></body></html>"); label.setBorder(HintUtil.createHintBorder()); label.setBackground(HintUtil.INFORMATION_COLOR); label.setOpaque(true); HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(patternHelp), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1); } public void mouseExited(MouseEvent e) { HintManager.getInstance().hideAllHints(); } }); }

Target:
private void createUIComponents() { patternHelp = new HyperlinkLabel(""); Icon infoIcon = SonarLintIcons.INFO; patternHelp.setIcon(infoIcon); patternHelp.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { final JLabel label = new JLabel("<<html><body style=\"margin-bottom:1pt\">" + "Configure GLOB patterns to be applied to files in all projects.<br/><br/><b>Examples:</b><br/>" + "<table border=\"1\" cellpadding=\"1\" cellspacing=\"0\"><tr><td><pre>** *{!.java}</pre></td>" + "<td>Exclude everything except Java files</td></tr></table></body></html>"); label.setBorder(HintUtil.createHintBorder()); label.setBackground(HintUtil.INFORMATION_COLOR); label.setOpaque(true); HintManager.getInstance().showHint(label, RelativePoint.getSouthWestOf(patternHelp), HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE, -1); } @Override public void mouseExited(MouseEvent e) { HintManager.getInstance().hideAllHints(); } }); }
Source:
private short getNewUid() { write.lock(); try { this.maxUid += 1; } finally { write.unlock(); } return this.maxUid; }

Target:
private short getNewUid() { write.lock(); try { this.maxUid += 1; return this.maxUid; } finally { write.unlock(); } }
Source:
public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()){ return false; } boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); if(!toReturn) break; } return toReturn; }

Target:
public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()){ return false; } boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); if(!toReturn) { break; } } return toReturn; }
Source:
public void setupMocks() { MockitoAnnotations.initMocks(this); when(uris.isEntityNamespace(0)).thenReturn(true); when(uris.getHost()).thenReturn(DOMAIN); URIBuilder b = new URIBuilder(); b.setScheme("https"); b.setHost("acme.test"); when(uris.builder()).thenReturn(b); }

Target:
public void setupMocks() { MockitoAnnotations.initMocks(this); uris = new Uris("https", DOMAIN, 443, new long[] {0}); }
Source:
public static Map<String,String> parseLine(VCFHeaderVersion version, String valueLine, List<String> expectedTagOrder) { return mapping.get(version).parseLine(valueLine,expectedTagOrder,Collections.emptySet()); }

Target:
public static Map<String,String> parseLine(VCFHeaderVersion version, String valueLine, List<String> expectedTagOrder) { return parseLine(version, valueLine, expectedTagOrder, Collections.emptyList()); }
Source:
protected String buildTransactionDescription(ConcurStandardAccountingExtractDetailLine saeLine) { String formattedEndDate = dateFormatter.apply(saeLine.getReportEndDate(), ConcurConstants.DATE_FORMAT); return new StringBuilder(INITIAL_BUILDER_SIZE) .append(StringUtils.left(saeLine.getEmployeeLastName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(',').append(StringUtils.left(saeLine.getEmployeeFirstName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(',').append(formattedEndDate) .toString(); }

Target:
protected String buildTransactionDescription(ConcurStandardAccountingExtractDetailLine saeLine) { String formattedEndDate = dateTimeService.toString(saeLine.getReportEndDate(), ConcurConstants.DATE_FORMAT); return new StringBuilder(INITIAL_BUILDER_SIZE) .append(StringUtils.left(saeLine.getEmployeeLastName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(COMMA_CHAR).append(StringUtils.left(saeLine.getEmployeeFirstName(), NAME_LENGTH_FOR_DESCRIPTION)) .append(COMMA_CHAR).append(formattedEndDate) .toString(); }
Source:
public void doQuery(List<ITmfStateInterval> stateInfo, long t) throws TimeRangeException, StateSystemDisposedException { checkValidTime(t); Deque<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); try { while (!queue.isEmpty()) { HTNode currentNode = queue.pop(); if ((currentNode.getNodeType() == HTNode.NodeType.CORE)) { queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } currentNode.writeInfoFromNode(stateInfo, t); } } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }

Target:
public void doQuery(List<ITmfStateInterval> stateInfo, long t) throws TimeRangeException, StateSystemDisposedException { checkValidTime(t); Deque<HTNode> queue = new LinkedList<>(); queue.add(fSht.getRootNode()); try { while (!queue.isEmpty()) { HTNode currentNode = queue.pop(); if (currentNode.getNodeType() == HTNode.NodeType.CORE) { queue.addAll(fSht.selectNextChildren((CoreNode) currentNode, t)); } currentNode.writeInfoFromNode(stateInfo, t); } } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }
Source:
public List<Hotspot> proteinLocationHotspotsFilter(List<Hotspot> hotspots, ProteinLocation proteinLocation) { int start = proteinLocation.getStart(); int end = proteinLocation.getEnd(); String type = proteinLocation.getMutationType(); List<Hotspot> result = new ArrayList<>(); for (Hotspot hotspot: hotspots) { boolean validPosition = true; int hotspotStart = proteinPositionResolver.extractProteinPos(hotspot.getResidue()).getStart(); int hotspotStop = proteinPositionResolver.extractProteinPos(hotspot.getResidue()).getEnd(); validPosition &= (start <= hotspotStop && end >= hotspotStart); boolean validMissense = type.equals("Missense_Mutation") && (hotspot.getType().contains("3d") || hotspot.getType().contains("single residue")); boolean validInFrameInsertion = type.equals("In_Frame_Ins") || type.equals("In_Frame_Ins") && (hotspot.getType().contains("in-frame")); boolean validInFrameDeletion = type.equals("In_Frame_Del") || type.equals("In_Frame_Del") && (hotspot.getType().contains("in-frame")); boolean validSplice = type.equals("Splice_Site") || type.equals("Splice_Region") && (hotspot.getType().contains("splice")); if (validPosition && (validMissense || validInFrameInsertion || validInFrameDeletion || validSplice)) { result.add(hotspot); } } return result; }

Target:
public List<Hotspot> proteinLocationHotspotsFilter(List<Hotspot> hotspots, ProteinLocation proteinLocation) { int start = proteinLocation.getStart(); int end = proteinLocation.getEnd(); String type = proteinLocation.getMutationType(); List<Hotspot> result = new ArrayList<>(); for (Hotspot hotspot: hotspots) { int hotspotStart = proteinPositionResolver.extractProteinPos(hotspot.getResidue()).getStart(); int hotspotStop = proteinPositionResolver.extractProteinPos(hotspot.getResidue()).getEnd(); boolean validPosition = start <= hotspotStop && end >= hotspotStart; boolean validMissense = type.equals("Missense_Mutation") && (hotspot.getType().contains("3d") || hotspot.getType().contains("single residue")); boolean validInFrameInsertion = type.equals("In_Frame_Ins") || type.equals("In_Frame_Ins") && (hotspot.getType().contains("in-frame")); boolean validInFrameDeletion = type.equals("In_Frame_Del") || type.equals("In_Frame_Del") && (hotspot.getType().contains("in-frame")); boolean validSplice = type.equals("Splice_Site") || type.equals("Splice_Region") && (hotspot.getType().contains("splice")); if (validPosition && (validMissense || validInFrameInsertion || validInFrameDeletion || validSplice)) { result.add(hotspot); } } return result; }
Source:
public synchronized void start() { logger.info("{} TaildirSource source starting with directory: {}", getName(), filePaths); try { reader = new ReliableTaildirEventReader.Builder() .filePaths(filePaths) .headerTable(headerTable) .positionFilePath(positionFilePath) .skipToEnd(skipToEnd) .addByteOffset(byteOffsetHeader) .cachePatternMatching(cachePatternMatching) .annotateFileName(fileHeader) .fileNameHeader(fileHeaderKey) .build(); } catch (IOException e) { throw new FlumeException("Error instantiating ReliableTaildirEventReader", e); } for (Entry<Long, TailFile> entry : reader.getTailFiles().entrySet()) { inodePositionMap.put(entry.getKey() + "", entry.getValue().getPos() + ""); inodePathMap.put(entry.getKey() + "", entry.getValue().getPath() + ""); } idleFileChecker = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("idleFileChecker").build()); idleFileChecker.scheduleWithFixedDelay(new idleFileCheckerRunnable(), idleTimeout, checkIdleInterval, TimeUnit.MILLISECONDS); super.start(); logger.debug("TaildirSource started"); sourceCounter.start(); }

Target:
public synchronized void start() { logger.info("{} TaildirSource source starting with directory: {}", getName(), filePaths); try { reader = new ReliableTaildirEventReader.Builder() .filePaths(filePaths) .headerTable(headerTable) .positionFilePath(positionFilePath) .skipToEnd(skipToEnd) .addByteOffset(byteOffsetHeader) .cachePatternMatching(cachePatternMatching) .writePosOnCommit(writePosOnCommit) .annotateFileName(fileHeader) .fileNameHeader(fileHeaderKey) .build(); } catch (IOException e) { throw new FlumeException("Error instantiating ReliableTaildirEventReader", e); } if (writePosOnCommit) { for (Entry<Long, TailFile> entry : reader.getTailFiles().entrySet()) { inodePositionMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue().getPos())); inodePathMap.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue().getPath())); } } idleFileChecker = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("idleFileChecker").build()); idleFileChecker.scheduleWithFixedDelay(new idleFileCheckerRunnable(), idleTimeout, checkIdleInterval, TimeUnit.MILLISECONDS); if (!writePosOnCommit) { positionWriter = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("positionWriter").build()); positionWriter.scheduleWithFixedDelay(new PositionWriterRunnable(), writePosInitDelay, writePosInterval, TimeUnit.MILLISECONDS); } super.start(); logger.debug("TaildirSource started"); sourceCounter.start(); }
Source:
public Set<String> getWhitelist() { return whitelistedIDs; }

Target:
public Set getWhitelist() { return Collections.unmodifiableSet(whitelistedIDs); }
Source:
protected UserReference convertToType(Type targetType, Object value) { if (value == null) { return null; } WikiReference currentWikiReference = this.xcontextProvider.get().getWikiReference(); return this.userReferenceResolver.resolve(value.toString(), currentWikiReference); }

Target:
protected UserReference convertToType(Type targetType, Object value) { if (value == null) { return null; } return this.userReferenceResolver.resolve(value.toString()); }
Source:
private boolean isDTreeItemContainerOwnedTreeItems(Notification notification) { return notification.getFeature() == TreePackage.Literals.DTREE_ITEM_CONTAINER__OWNED_TREE_ITEMS && notification.getNotifier() instanceof DTreeItemContainer; }

Target:
private boolean isDTreeItemContainerOwnedTreeItems(Notification notification) { return notification.getFeature() == TreePackage.Literals.DTREE_ITEM_CONTAINER__OWNED_TREE_ITEMS; }
Source:
public static View hitTest(View view, float x, float y, @Nullable Predicate<View> viewSelector) { if (!ViewUtil.pointInView(view, x, y)) { return null; } if (!(view instanceof ViewGroup)) { return null; } final ViewGroup viewGroup = (ViewGroup)view; for (int i = viewGroup.getChildCount() - 1; i >= 0; --i) { final View child = viewGroup.getChildAt(i); if (child.getVisibility() == View.INVISIBLE) { continue; } if (viewSelector != null && !viewSelector.apply(child)) { continue; } PointF localPoint = new PointF(); if (ViewUtil.isTransformedPointInView(viewGroup, child, x, y, localPoint)) { if (child instanceof ViewGroup) { return hitTest(child, localPoint.x, localPoint.y, viewSelector); } else { return child; } } } return viewGroup; }

Target:
public static View hitTest(View view, float x, float y, @Nullable Predicate<View> viewSelector) { if (!ViewUtil.pointInView(view, x, y)) { return null; } if (!(view instanceof ViewGroup)) { return null; } final ViewGroup viewGroup = (ViewGroup)view; for (int i = viewGroup.getChildCount() - 1; i >= 0; --i) { final View child = viewGroup.getChildAt(i); if (child.getVisibility() != View.VISIBLE) { continue; } if (viewSelector != null && !viewSelector.apply(child)) { continue; } PointF localPoint = new PointF(); if (ViewUtil.isTransformedPointInView(viewGroup, child, x, y, localPoint)) { if (child instanceof ViewGroup) { return hitTest(child, localPoint.x, localPoint.y, viewSelector); } else { return child; } } } return viewGroup; }
Source:
public static String map(org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus glusterVolumeStatus, String template) { switch (glusterVolumeStatus) { case UP: return GlusterState.UP.name(); case DOWN: return GlusterState.DOWN.name(); default: return null; } }

Target:
public static GlusterState map(org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus glusterVolumeStatus, String template) { switch (glusterVolumeStatus) { case UP: return GlusterState.UP; case DOWN: return GlusterState.DOWN; default: return null; } }
Source:
public static void readResponse(List<String> parameters, Map<String, String> parameterMap) { log.debug("Start finding parameters in response data and create extractors."); for (String parameter : parameters) { ExtractorData extractor = createExtractorForParameter(parameter, parameterMap.get(parameter)); if (extractor != null) { getListOfExtractor().add(extractor); } } log.debug("Processing of sample results ended."); updateJmxFile(parameterMap); }

Target:
public static void readResponse(List<String> parameters, Map<String, String> parameterMap) { log.debug("Start finding parameters in response data and create extractors."); for (String parameter : parameters) { ExtractorData extractor = createExtractorForParameter(parameter, parameterMap.get(parameter)); if (extractor != null) { getListOfExtractor().add(extractor); } } log.debug("Processing of finding parameters in response data and creation of extractors ended."); updateJmxFile(parameterMap); }
Source:
public void lookupByNameCaching() throws Throwable { when(registry.lookupByName(any())).thenReturn(java.util.Optional.of("malaFama")); BaseService service = new Utils.InvalidNamedAugmentedMethodService(); Method method = BaseService.class.getMethod("augmented"); injectParamsFromContextServiceMethodInvoker.invoke(service, method, null); injectParamsFromContextServiceMethodInvoker.invoke(service, method, null); verify(registry).lookupByName(any()); }

Target:
public void lookupByNameCaching() throws Throwable { when(registry.lookupByName(any())).thenReturn(java.util.Optional.of("malaFama")); BaseService service = new Utils.InvalidNamedAugmentedMethodService(); Method method = BaseService.class.getMethod("augmented"); injectParamsFromContextServiceMethodInvoker.invoke(service, method, null); injectParamsFromContextServiceMethodInvoker.invoke(service, method, null); verify(registry, times(1)).lookupByName(any()); }
Source:
public void visitNamespaceStatement(NamespaceStatementTree tree) { aliases.clear(); currentNamespace = tree.namespaceName() != null ? QualifiedName.create(tree.namespaceName()) : null; super.visitNamespaceStatement(tree); boolean isBracketedNamespace = tree.openCurlyBrace() != null; if (isBracketedNamespace) { currentNamespace = null; aliases.clear(); } }

Target:
public void visitNamespaceStatement(NamespaceStatementTree tree) { aliases.clear(); currentNamespace = tree.namespaceName() != null ? QualifiedName.create(tree.namespaceName()) : null; super.visitNamespaceStatement(tree); boolean isBracketedNamespace = tree.openCurlyBrace() != null; if (isBracketedNamespace) { resetNamespace(); } }
Source:
public void shouldUseUsernameAsNamespaceWhenCreatingWorkspaceWithoutSpecifiedNamespace() throws Exception { final WorkspaceConfigDto configDto = createConfigDto(); final WorkspaceImpl workspace = createWorkspace(configDto); when(wsManager.createWorkspace( any(WorkspaceConfig.class), anyString(), anyMapOf(String.class, String.class))) .thenReturn(workspace); final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .body(configDto) .when() .post( SECURE_PATH + "/workspace" + "?attribute=stackId:stack123" + "&attribute=factoryId:factory123" + "&attribute=custom:custom:value"); assertEquals(response.getStatusCode(), 201); assertEquals( new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); verify(wsManager) .createWorkspace( anyObject(), eq(NAMESPACE), eq( ImmutableMap.of( "stackId", "stack123", "factoryId", "factory123", "custom", "custom:value"))); }

Target:
public void shouldUseUsernameAsNamespaceWhenCreatingWorkspaceWithoutSpecifiedNamespace() throws Exception { final WorkspaceConfigDto configDto = createConfigDto(); final WorkspaceImpl workspace = createWorkspace(configDto); when(wsManager.createWorkspace(any(WorkspaceConfig.class), anyString(), any())) .thenReturn(workspace); final Response response = given() .auth() .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD) .contentType("application/json") .body(configDto) .when() .post( SECURE_PATH + "/workspace" + "?attribute=stackId:stack123" + "&attribute=factoryId:factory123" + "&attribute=custom:custom:value"); assertEquals(response.getStatusCode(), 201); assertEquals( new WorkspaceImpl(unwrapDto(response, WorkspaceDto.class), TEST_ACCOUNT), workspace); verify(wsManager) .createWorkspace( anyObject(), eq(NAMESPACE), eq( ImmutableMap.of( "stackId", "stack123", "factoryId", "factory123", "custom", "custom:value"))); }
Source:
public void handle(YamlObject<?> obj, YamlParseContext context) { YamlSeq seq = obj.seq(); for (YamlObject o : seq) { YamlMap r = o.map(); Rule rule = factory.style.createRule(); featureStyle.rules().add(rule); rule.setName(r.str("name")); rule.setTitle(r.str("title")); rule.setAbstract(r.str("abstract")); context.push( r, "legend", new GraphicParser(factory) { @Override protected void graphic(Graphic g) { rule.setLegend(g); } }); if (r.has("filter")) { try { rule.setFilter(ECQL.toFilter(Util.removeExpressionBrackets(r.str("filter")))); } catch (CQLException e) { throw new RuntimeException("Error parsing filter", e); } } rule.setElseFilter(r.boolOr("else", false)); @Nullable ScaleRange range = Util.defaultForNull(parseScale(r), parseZoom(r, context)); if (range != null) { range.applyTo(rule); } context.push(r, "symbolizers", new SymbolizersParser(rule, factory)); } }

Target:
public void handle(YamlObject<?> obj, YamlParseContext context) { YamlSeq seq = obj.seq(); for (YamlObject o : seq) { YamlMap r = o.map(); Rule rule = factory.style.createRule(); featureStyle.rules().add(rule); rule.setName(r.str("name")); if (r.has("title")) { rule.setTitle(r.str("title")); } if (r.has("abstract")) { rule.setAbstract(r.str("abstract")); } rule.setTitle(r.str("title")); rule.setAbstract(r.str("abstract")); context.push( r, "legend", new GraphicParser(factory) { @Override protected void graphic(Graphic g) { rule.setLegend(g); } }); if (r.has("filter")) { try { rule.setFilter(ECQL.toFilter(Util.removeExpressionBrackets(r.str("filter")))); } catch (CQLException e) { throw new RuntimeException("Error parsing filter", e); } } rule.setElseFilter(r.boolOr("else", false)); @Nullable ScaleRange range = Util.defaultForNull(parseScale(r), parseZoom(r, context)); if (range != null) { range.applyTo(rule); } context.push(r, "symbolizers", new SymbolizersParser(rule, factory)); } }