auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public HashMap<String, String> getSearchFields() { <START> return ProzesskopieForm.getSearchFieldsForCatalogue(opacKatalog); <END> }</code><technical_language>Returns empty list if opacKatalog is null (first start of meta-data editor). Fix: String catalogue = opacKatalog; if(catalogue == null) { List<String> allOpacCatalogues = ProzesskopieForm.getAllOpacCatalogues(); if(!allOpacCatalogues.isEmpty()){ catalogue = allOpacCatalogues.get(0); } } return ProzesskopieForm.getSearchFieldsForCatalogue(catalogue); ProzesskopieForm.getAllOpacCatalogues() needs declared static do so</technical_language>

Target:
public HashMap<String, String> getSearchFields() { if (opacKatalog == null || opacKatalog.isEmpty()) { ProzesskopieForm pkf = new ProzesskopieForm(); List<String> allOpacCatalogues = pkf.getAllOpacCatalogues(); if (!allOpacCatalogues.isEmpty()) { opacKatalog = allOpacCatalogues.get(0); } } return ProzesskopieForm.getSearchFieldsForCatalogue(opacKatalog); }
Source:
<code>public StatisticsLoadBalance() { <START> CpuUsageService cpuUsageService = new CpuUsageServiceImpl(100L, 500L); <END> cpuUsageService.addListener("statisticsloadbalance", (ip, cpu) -> cpuUsage.put(ip, cpu)); }</code><technical_language>Hi, I configurable</technical_language>

Target:
public StatisticsLoadBalance() { long collectCpuUsageInMill = Long.parseLong(ConfigurationUtils.getProperty("mill.to.check.cpu.usage.availability")); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(this.getClass().getSimpleName(), true)); executor.scheduleAtFixedRate(this::removeStatisticsWhichServerIsDown, collectCpuUsageInMill, collectCpuUsageInMill, TimeUnit.MILLISECONDS); }
Source:
<code>public static <T> T deserializeObject(ObjectMapper mapper, Object payload, Class<T> clazz, JsonSerializer customJsonSerializer) throws JsonProcessingException { if (customJsonSerializer == null) { <START> if (clazz.isAssignableFrom(String.class)){ <END> return (T)mapper.writeValueAsString(payload); } else { return mapper.convertValue(payload, clazz); } } else { ByteArrayOutputStream sourceStream = new ByteArrayOutputStream(); customJsonSerializer.serialize(sourceStream, payload); return customJsonSerializer.deserialize(new ByteArrayInputStream(sourceStream.toByteArray()), createInstance(clazz)); } }</code><technical_language>space curly brace</technical_language>

Target:
public static <T> T deserializeObject(ObjectMapper mapper, Object payload, Class<T> clazz, JsonSerializer customJsonSerializer) throws JsonProcessingException { if (customJsonSerializer == null) { if (clazz.isAssignableFrom(String.class)) { return (T)mapper.writeValueAsString(payload); } else { return mapper.convertValue(payload, clazz); } } ByteArrayOutputStream sourceStream = new ByteArrayOutputStream(); customJsonSerializer.serialize(sourceStream, payload); return customJsonSerializer.deserialize(new ByteArrayInputStream(sourceStream.toByteArray()), createInstance(clazz)); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { pipelineConfigurer.createDataset(config.fileSetName, FileSet.class); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); <START> if (inputSchema != null) { <END> config.validate(inputSchema); } }</code><technical_language>for a similar reason predictor, error if input schema is null</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { pipelineConfigurer.createDataset(config.fileSetName, FileSet.class); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); Preconditions.checkArgument(inputSchema != null, "Input Schema must be a known constant."); config.validate(inputSchema); }
Source:
<code><START> private static Set<UnitType> findTargets( <END> final UnitType unitType, final Set<UnitType> unitTypes, final Set<UnitType> enemyUnitTypes) { final Set<UnitType> targets = new HashSet<>(enemyUnitTypes); targets.removeAll(UnitAttachment.get(unitType).getCanNotTarget()); if (!unitTypes.stream().anyMatch(Matches.unitTypeIsDestroyer())) { for (final UnitType target : targets) { if (UnitAttachment.get(target).getCanNotBeTargetedBy().contains(unitType)) { targets.remove(target); } } } return targets; }</code><technical_language>Method findTargets a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring</technical_language>

Target:
private static Set<UnitType> findTargets( final UnitType unitType, final Set<UnitType> unitTypes, final Set<UnitType> enemyUnitTypes) { final Set<UnitType> targets = new HashSet<>(enemyUnitTypes); targets.removeAll(UnitAttachment.get(unitType).getCanNotTarget()); return unitTypes.stream().anyMatch(Matches.unitTypeIsDestroyer()) ? targets : targets.stream() .filter( target -> !UnitAttachment.get(target).getCanNotBeTargetedBy().contains(unitType)) .collect(Collectors.toSet()); }
Source:
<code>public TextTranslationServiceImpl(StoreOntologyService storeOntologyService) { this.namedClassTypes = new ConcurrentHashMap<>(); try { <START> this.urls.addAll(storeOntologyService.retrieveOntologyURLs()); <END> } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>thrilled mutability fine</technical_language>

Target:
public TextTranslationServiceImpl(StoreOntologyService storeOntologyService) { this.namedClassTypes = new ConcurrentHashMap<>(); this.storeOntologyService = storeOntologyService; }
Source:
<code>public void storeCommand() throws PersistenceException { final File inputFile = getInputFile(); if (inputFile == null) { return; } int totalFiles = 0; try { totalFiles = totalFileCount(inputFile); } catch (IOException e) { console.println("Unable to read directory"); } List<Map<String, Object>> importResults = new ArrayList<>(); console.println("Found " + totalFiles + " files to import\n"); try (Stream<Path> ingestStream = Files.walk(inputFile.toPath(), FileVisitOption.FOLLOW_LINKS)) { ingestStream .filter(Files::isRegularFile) .map(Path::toFile) .map(this::processFile) .filter(Objects::nonNull) <START> .forEach(importResults::add); <END> } catch (IOException e) { console.println("Unable to import files."); throw new UncheckedIOException(e); } persistentStore.add(type, importResults); console.println("Imported " + importResults.size() + " records \n"); }</code><technical_language>I this OOM is files stored once. do files in batches avoid map large</technical_language>

Target:
public void storeCommand() throws PersistenceException { final File inputFile = getInputFile(); if (inputFile == null) { return; } int totalFiles = 0; long totalImport = 0; try { totalFiles = totalFileCount(inputFile); } catch (IOException e) { console.println("Unable to read directory"); } List<Map<String, Object>> importResults = new ArrayList<>(); console.println("Found " + totalFiles + " files to import\n"); try (Stream<Path> ingestStream = Files.walk(inputFile.toPath(), FileVisitOption.FOLLOW_LINKS)) { List<Path> regularFiles = ingestStream.filter(Files::isRegularFile).collect(Collectors.toList()); for (Collection<Path> batch : Lists.partition(regularFiles, batchSize)) { batch .stream() .map(Path::toFile) .map(this::processFile) .filter(Objects::nonNull) .forEach(importResults::add); persistentStore.add(type, importResults); totalImport += importResults.size(); } } catch (IOException e) { console.println("Unable to import files."); throw new UncheckedIOException(e); } console.println("Imported " + totalImport + " records \n"); }
Source:
<code>private WritableSupplier<IndexedMultivalue<IndexedInts>> readMultiValuedColum(VERSION version, ByteBuffer buffer) { switch (version) { case UNCOMPRESSED_MULTI_VALUE: return VSizeIndexed.readFromByteBuffer(buffer).asWritableSupplier(); case COMPRESSED: return CompressedVSizeIndexedSupplier.fromByteBuffer(buffer, byteOrder); } <START> throw new IAE("Unsupported version[%s]", version); <END> }</code><technical_language>Suggest Unsupported multi-valued version</technical_language>

Target:
private WritableSupplier<IndexedMultivalue<IndexedInts>> readMultiValuedColum(VERSION version, ByteBuffer buffer) { switch (version) { case UNCOMPRESSED_MULTI_VALUE: return VSizeIndexed.readFromByteBuffer(buffer).asWritableSupplier(); case COMPRESSED: return CompressedVSizeIndexedSupplier.fromByteBuffer(buffer, byteOrder); } throw new IAE("Unsupported multi-value version[%s]", version); }
Source:
<code>public static String stackTrace(Exception ex) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); String str = writer.toString(); <START> return str; <END> }</code><technical_language>combine 2 lines</technical_language>

Target:
public static String stackTrace(Exception ex) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); return writer.toString(); }
Source:
<code><START> private Topology readTopology() throws Exception { <END> try { final byte[] data = getCurator().getData().forPath(getSubscriptionPath(NODE_TOPOLOGY)); final Topology result = objectMapper.readValue(data, Topology.class); getLog().info("Topology is {}", result); return result; } catch (final IOException ex) { throw new OldSubscriptionFormatException(); } catch (KeeperException.NoNodeException ex) { throw new SubscriptionNotInitializedException(getSubscriptionId()); } }</code><technical_language>runtime exceptions here. I is process Exception in this method throw runtime exception well, is basically do in methods this method</technical_language>

Target:
private Topology readTopology() throws NakadiRuntimeException, OldSubscriptionFormatException, SubscriptionNotInitializedException { try { final byte[] data = getCurator().getData().forPath(getSubscriptionPath(NODE_TOPOLOGY)); final Topology result = objectMapper.readValue(data, Topology.class); getLog().info("Topology is {}", result); return result; } catch (final IOException ex) { throw new OldSubscriptionFormatException(); } catch (KeeperException.NoNodeException ex) { throw new SubscriptionNotInitializedException(getSubscriptionId()); } catch (final Exception ex) { throw new NakadiRuntimeException(ex); } }
Source:
<code><START> private static KafkaConsumer<String, ChangeEvent> buildKafkaConsumer( <END> String servers, String consumerId, Map<String, Class<? extends ChangeEvent>> topicToClass, int batchSize) { Properties props = new Properties(); props.put("bootstrap.servers", servers); props.put("group.id", consumerId); props.put("max.poll.interval.ms", "600000"); props.put("enable.auto.commit", "false"); props.put("max.poll.records", System.getProperty(MAX_POLL_PROPERTY, String.valueOf(batchSize))); props.put("max.partition.fetch.bytes", System.getProperty(MAX_FETCH_PROPERTY, String.valueOf(batchSize * 1024))); log.info("Creating consumer {}", consumerId); return new KafkaConsumer<>(props, new StringDeserializer(), new JsonDeserializer<>(topicToClass)); }</code><technical_language>I Kafka details belong here. Kafka-specific in Kafka classes IMO</technical_language>

Target:
private static KafkaConsumer<String, ChangeEvent> buildKafkaConsumer( String servers, String consumerId, Map<String, Class<? extends ChangeEvent>> topicToClass, int batchSize) { Properties props = new Properties(); props.put("bootstrap.servers", servers); props.put("group.id", consumerId); props.put("max.poll.interval.ms", "600000"); props.put("enable.auto.commit", "false"); props.put("max.poll.records", System.getProperty(KafkaPoller.MAX_POLL_PROPERTY, String.valueOf(batchSize))); props.put("max.partition.fetch.bytes", System.getProperty(KafkaPoller.MAX_FETCH_PROPERTY, String.valueOf(batchSize * 1024))); log.info("Creating consumer {}", consumerId); return new KafkaConsumer<>(props, new StringDeserializer(), new JsonDeserializer<>(topicToClass)); }
Source:
<code>protected void makeAuditRecord( final float time, final String messageType, final Map<String, Serializable> actionParams, String className ) { AuditHelper.audit( PentahoSessionHolder.getSession() != null ? PentahoSessionHolder.getSession().getId() : "", getValue( actionParams, ActionUtil.INVOKER_ACTIONUSER ), getValue( actionParams, ActionUtil.INVOKER_STREAMPROVIDER ), className, <START> String.format( getValue( actionParams, ActionUtil.INVOKER_ACTIONID ) ), <END> messageType, getValue( actionParams, ActionUtil.QUARTZ_LINEAGE_ID ), null, time, null ); }</code><technical_language>remove String.format</technical_language>

Target:
protected void makeAuditRecord( final float time, final String messageType, final Map<String, Serializable> actionParams, String className ) { AuditHelper.audit( PentahoSessionHolder.getSession() != null ? PentahoSessionHolder.getSession().getId() : "", getValue( actionParams, ActionUtil.INVOKER_ACTIONUSER ), getValue( actionParams, ActionUtil.INVOKER_STREAMPROVIDER ), className, getValue( actionParams, ActionUtil.INVOKER_ACTIONID ), messageType, getValue( actionParams, ActionUtil.QUARTZ_LINEAGE_ID ), null, time, null ); }
Source:
<code><START> private Set<ID> toSet(Iterable<ID> ids) { <END> Set<ID> keys = emptySet(); if (ids instanceof Set) keys = (Set<ID>)ids; else { Iterator<ID> itr = ids.iterator(); if (itr.hasNext()) { ID key = itr.next(); keys = key instanceof Comparable ? new TreeSet<>() : new HashSet<>(); keys.add(key); while (itr.hasNext()) { key = itr.next(); keys.add(key); } } } return keys; }</code><technical_language>Try this private Set<ID> toSet(Iterable<ID> ids) { if (ids instanceof Set) return (Set<ID>)ids; Iterator<ID> itr = ids.iterator(); if (!itr.hasNext()) return emptySet(); ID key = itr.next(); Set<ID> keys = key instanceof Comparable ? new TreeSet<>() : new HashSet<>(); keys.add(key); while (itr.hasNext()) { key = itr.next(); keys.add(key); } return keys; }</technical_language>

Target:
private Set<ID> toSet(Iterable<ID> ids) { if (ids instanceof Set) return (Set<ID>)ids; Iterator<ID> itr = ids.iterator(); if (!itr.hasNext()) return emptySet(); ID key = itr.next(); Set<ID> keys = key instanceof Comparable ? new TreeSet<>() : new HashSet<>(); keys.add(key); while (itr.hasNext()) { key = itr.next(); keys.add(key); } return keys; }
Source:
<code>public long getNumberOfAssociations(Session session) { final InfinispanRemoteDatastoreProvider datastoreProvider = getProvider( session.getSessionFactory() ); final SessionFactoryImplementor sessionFactoryImplementor = getSessionFactoryImplementor( session.getSessionFactory() ); Collection<CollectionPersister> persisters = sessionFactoryImplementor.getMetamodel().collectionPersisters().values(); long totalCount = 0; for ( CollectionPersister ep : persisters ) { OgmCollectionPersister persister = (OgmCollectionPersister) ep; String tableName = persister.getTableName(); SingleTableOgmEntityPersister owningPersister = (SingleTableOgmEntityPersister) persister.getOwnerEntityPersister().getEntityPersister(); String ownerTableName = owningPersister.getTableName(); RemoteCache<Object, Object> cache = datastoreProvider.getCache( tableName ); if ( !( cache instanceof TransactionalRemoteCacheImpl ) ) { totalCount += countAssociations( tableName, ownerTableName, datastoreProvider ); <START> continue; <END> } final String[] ownerIdentifyingColumnNames = getIdentityOwnerColumnNames( ownerTableName, datastoreProvider ); totalCount += TransactionalRemoteCacheCounter.countAssociations( (TransactionalRemoteCacheImpl) cache, persister, session, ownerIdentifyingColumnNames ); } return totalCount; }</code><technical_language>A small note, a if-then-else instead of continue, please? I find code easier follow continue</technical_language>

Target:
public long getNumberOfAssociations(Session session) { final InfinispanRemoteDatastoreProvider datastoreProvider = getProvider( session.getSessionFactory() ); final SessionFactoryImplementor sessionFactoryImplementor = getSessionFactoryImplementor( session.getSessionFactory() ); Collection<CollectionPersister> persisters = sessionFactoryImplementor.getMetamodel().collectionPersisters().values(); long totalCount = 0; for ( CollectionPersister ep : persisters ) { OgmCollectionPersister persister = (OgmCollectionPersister) ep; String tableName = persister.getTableName(); SingleTableOgmEntityPersister owningPersister = (SingleTableOgmEntityPersister) persister.getOwnerEntityPersister().getEntityPersister(); String ownerTableName = owningPersister.getTableName(); RemoteCache<Object, Object> cache = datastoreProvider.getCache( tableName ); if ( cache instanceof TransactionalRemoteCacheImpl ) { final String[] ownerIdentifyingColumnNames = getIdentityOwnerColumnNames( ownerTableName, datastoreProvider ); totalCount += TransactionalRemoteCacheCounter.countAssociations( (TransactionalRemoteCacheImpl) cache, persister, session, ownerIdentifyingColumnNames ); } else { totalCount += countAssociations( tableName, ownerTableName, datastoreProvider ); } } return totalCount; }
Source:
<code>private void validateNewTraceName() { String newTraceName = fNewTraceNameText.getText(); IWorkspace workspace = fTrace.getResource().getWorkspace(); IStatus nameStatus = workspace.validateName(newTraceName, IResource.FOLDER); if ("".equals(newTraceName)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } IPath newPath = new Path(newTraceName); IContainer parentFolder = fTrace.getResource().getParent(); <START> if (parentFolder.getFolder(newPath).exists() || parentFolder.getFile(newPath).exists()) { <END> updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }</code><technical_language>findMember instead of</technical_language>

Target:
private void validateNewTraceName() { String newTraceName = fNewTraceNameText.getText(); IWorkspace workspace = fTrace.getResource().getWorkspace(); IStatus nameStatus = workspace.validateName(newTraceName, IResource.FOLDER); if ("".equals(newTraceName)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } IContainer parentFolder = fTrace.getResource().getParent(); if (parentFolder.findMember(newTraceName) != null) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }
Source:
<code><START> protected ClientId(String clientId, String clientSecret) { <END> this.clientId = Preconditions.checkNotNull(clientId); this.clientSecret = clientSecret; }</code><technical_language>mark constructors @Deprecated instead of deleting / reducing visibility? easier transition versions if deprecate first, delete later</technical_language>

Target:
public ClientId(String clientId, String clientSecret) { this.clientId = Preconditions.checkNotNull(clientId); this.clientSecret = clientSecret; }
Source:
<code>public void acronym(String text, String definition) { assertOpenBlock(); try { <START> currentBlock.write(text); currentBlock.write('('); currentBlock.write(definition); currentBlock.write(')'); <END> } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>good a test for this</technical_language>

Target:
public void acronym(String text, String definition) { assertOpenBlock(); characters(text); characters("("); characters(definition); characters(")"); }
Source:
<code>public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() <START> .credential(new AzureKeyCredential("{api_key}")) <END> .endpoint("{endpoint}") .buildAsyncClient(); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.instantiation return textAnalyticsAsyncClient; }</code><technical_language>azure_key_credential instead of api_key consistent terminology</technical_language>

Target:
public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.instantiation return textAnalyticsAsyncClient; }
Source:
<code>public LttngChannelColumn() { super(HEADER); <START> } <END></code><technical_language>Searching/filtering work, for a content field called 'Channel'</technical_language>

Target:
public LttngChannelColumn() { super(CHANNEL_HEADER); }
Source:
<code>protected void sendParams(HttpURLConnection request, Object params) throws IOException { request.setDoOutput(true); if (params != null) { request.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON + "; charset=" + CHARSET_UTF8); byte[] data = toJson(params).getBytes(CHARSET_UTF8); request.setFixedLengthStreamingMode(data.length); BufferedOutputStream output = new BufferedOutputStream( request.getOutputStream(), bufferSize); try { output.write(data); } finally { try { output.close(); <START> } catch (IOException ignored) { <END> } } } else request.setFixedLengthStreamingMode(0); }</code><technical_language>missing is swallowing exceptions flush. I.e. this change is ok, a flush finally capture errors occuring while writing final output</technical_language>

Target:
protected void sendParams(HttpURLConnection request, Object params) throws IOException { request.setDoOutput(true); if (params != null) { request.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON + "; charset=" + CHARSET_UTF8); byte[] data = toJson(params).getBytes(CHARSET_UTF8); request.setFixedLengthStreamingMode(data.length); BufferedOutputStream output = new BufferedOutputStream( request.getOutputStream(), bufferSize); try { output.write(data); output.flush(); } finally { try { output.close(); } catch (IOException ignored) { } } } else request.setFixedLengthStreamingMode(0); }
Source:
<code>public List<String> getUrls() { List<String> updateSites = new ArrayList<String>(); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String siteUrl = site.getUrl(); <START> int baseUrlEnd = siteUrl.indexOf("update-center.json"); <END> String siteBaseUrl = siteUrl.substring(0, baseUrlEnd); updateSites.add(siteBaseUrl + "updates/" + url); } return updateSites; }</code><technical_language>ant: return crappy results fail if UC configuration "update-center.json" in path. I skip URLs print warnings</technical_language>

Target:
public List<String> getUrls() { List<String> updateSites = new ArrayList<String>(); for (UpdateSite site : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String siteUrl = site.getUrl(); int baseUrlEnd = siteUrl.indexOf("update-center.json"); if (baseUrlEnd != -1) { String siteBaseUrl = siteUrl.substring(0, baseUrlEnd); updateSites.add(siteBaseUrl + "updates/" + url); } else { LOGGER.log(Level.WARNING, "Url {0} does not look like an update center:", siteUrl); } } return updateSites; }
Source:
<code>protected void checkPycaLibrary(SubscriptionContext ctx, CallExpression callExpression, Symbol calleeSymbol) { if (PYCA_ALGORITHM_METHODS.contains(calleeSymbol.fullyQualifiedName())) { List<Argument> arguments = callExpression.arguments(); if (arguments.size() < 2) { return; } <START> Argument argument = arguments.get(1); <END> if (argument.is(REGULAR_ARGUMENT)) { InferredType type = ((RegularArgument) argument).expression().type(); if (PYCA_VULNERABLE_MODES_AND_PADDING_SCHEMES.stream().anyMatch(type::canOnlyBe)) { ctx.addIssue(argument, MESSAGE); } } } }</code><technical_language>here, a keyword argument. need cover though, if eventually decide cover it, forget separate mode padding for Pyca</technical_language>

Target:
protected void checkPycaLibrary(SubscriptionContext ctx, CallExpression callExpression, Symbol calleeSymbol) { if ("cryptography.hazmat.primitives.ciphers.Cipher".equals(calleeSymbol.fullyQualifiedName())) { RegularArgument mode = TreeUtils.nthArgumentOrKeyword(1, "mode", callExpression.arguments()); if (mode != null) { InferredType type = mode.expression().type(); if (PYCA_VULNERABLE_MODES.stream().anyMatch(type::canOnlyBe)) { ctx.addIssue(mode, MESSAGE); } } return; } if (PYCA_RSA_KEY_METHODS.contains(calleeSymbol.fullyQualifiedName())) { RegularArgument padding = TreeUtils.nthArgumentOrKeyword(1, "padding", callExpression.arguments()); if (padding != null && padding.expression().type().canOnlyBe("cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15")) { ctx.addIssue(padding, MESSAGE); } } }
Source:
<code>public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { MessageProperties messageProperties = messagePropertiesConverter.toMessageProperties( properties, envelope, "UTF-8"); messageProperties.setMessageCount(0); messageProperties.setConsumerTag(consumerTag); messageProperties.setConsumerQueue(queue); Message message = new Message(body, messageProperties); try { invokeListener(message, getChannel()); <START> getChannel().basicAck(envelope.getDeliveryTag(), false); <END> } catch (Exception e) { getChannel().basicNack(envelope.getDeliveryTag(), false, requeueRejected); } }</code><technical_language>I is idempotent basicAck() target listener (e.g. AmqpHeaders.CHANNEL in SI app) more time..</technical_language>

Target:
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { MessageProperties messageProperties = SimpleDirectMessageListenerContainer.this.messagePropertiesConverter .toMessageProperties(properties, envelope, "UTF-8"); messageProperties.setMessageCount(0); messageProperties.setConsumerTag(consumerTag); messageProperties.setConsumerQueue(this.queue); Message message = new Message(body, messageProperties); try { invokeListener(getChannel(), message); if (this.ackRequired) { getChannel().basicAck(envelope.getDeliveryTag(), false); } } catch (Exception e) { if (this.ackRequired) { getChannel().basicNack(envelope.getDeliveryTag(), false, SimpleDirectMessageListenerContainer.this.requeueRejected); } } }
Source:
<code>public void initialize() throws Exception { super.init(); carbonHome = CarbonUtils.getCarbonHome(); String pathToCarbonXML = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "CARBON" + File.separator + "encryption" + File.separator + "carbon.xml"; String targetCarbonXML = carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator + "carbon.xml"; String pathToSymmetricProperties = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File .separator + "CARBON" + File.separator + "encryption" + File.separator + "symmetric-key.properties"; String securityFolder = carbonHome + File.separator + "repository" + File.separator + "resources" + File.separator + "security" + File.separator + "symmetric-key.properties"; serverConfigurationManager = new ServerConfigurationManager(automationContext); serverConfigurationManager.applyConfigurationWithoutRestart(new File(pathToSymmetricProperties), new File (securityFolder), false); serverConfigurationManager.applyConfigurationWithoutRestart(new File(pathToCarbonXML), new File (targetCarbonXML), false); serverConfigurationManager.restartGracefully(); super.init(); <START> uploadApp(); <END> readSymmetricKey(); }</code><technical_language>calling super.init() uploadApp()</technical_language>

Target:
public void initialize() throws Exception { super.init(); carbonHome = CarbonUtils.getCarbonHome(); String pathToCarbonXML = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "CARBON" + File.separator + "encryption" + File.separator + "carbon.xml"; String targetCarbonXML = carbonHome + File.separator + "repository" + File.separator + "conf" + File.separator + "carbon.xml"; String pathToSymmetricProperties = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File .separator + "CARBON" + File.separator + "encryption" + File.separator + "symmetric-key.properties"; String securityFolder = carbonHome + File.separator + "repository" + File.separator + "resources" + File.separator + "security" + File.separator + "symmetric-key.properties"; serverConfigurationManager = new ServerConfigurationManager(automationContext); serverConfigurationManager.applyConfigurationWithoutRestart(new File(pathToSymmetricProperties), new File (securityFolder), false); serverConfigurationManager.applyConfigurationWithoutRestart(new File(pathToCarbonXML), new File (targetCarbonXML), false); serverConfigurationManager.restartGracefully(); uploadApp(); readSymmetricKey(); }
Source:
<code>private boolean validateDestStorage(Guid imageId, Guid destDomainId) { DiskImage diskImage = getDiskImageById(imageId); <START> Guid storagePoolId = diskImage.getStoragePoolId().getValue(); <END> StorageDomainValidator validator = getValidator(destDomainId, storagePoolId); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); }</code><technical_language>getStoragePoolId() instead fetching disk</technical_language>

Target:
private boolean validateDestStorage(Guid imageId, Guid destDomainId) { StorageDomainValidator validator = getValidator(destDomainId, getStoragePoolId().getValue()); return validate(validator.isDomainExistAndActive()) && validate(validator.domainIsValidDestination()); }
Source:
<code>public void deserialize(byte[] message, Collector<RowData> out) throws IOException { if (message == null || message.length == 0) { return; } try { GenericRowData row = (GenericRowData) avroDeserializer.deserialize(message); GenericRowData before = null; <START> int index = rowType.getFieldIndex("before"); <END> if (index >= 0) { before = (GenericRowData) row.getField(index); } GenericRowData after = (GenericRowData) row.getField(rowType.getFieldIndex("after")); String op = row.getField(rowType.getFieldIndex("op")).toString(); if (OP_CREATE.equals(op) || OP_READ.equals(op)) { after.setRowKind(RowKind.INSERT); out.collect(after); } else if (OP_UPDATE.equals(op)) { if (before == null) { throw new IllegalStateException(String.format(REPLICA_IDENTITY_EXCEPTION, "UPDATE")); } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } else if (OP_DELETE.equals(op)) { if (before == null) { throw new IllegalStateException(String.format(REPLICA_IDENTITY_EXCEPTION, "DELETE")); } before.setRowKind(RowKind.DELETE); out.collect(before); } else { throw new IOException(format( "Unknown \"op\" value \"%s\". The Debezium Avro message is '%s'", op, new String(message))); } } catch (Throwable t) { throw new IOException(format( "Corrupt Debezium Avro message '%s'.", new String(message)), t); } }</code><technical_language>index of after. get index dynamically. implementation of debezium-json</technical_language>

Target:
public void deserialize(byte[] message, Collector<RowData> out) throws IOException { if (message == null || message.length == 0) { return; } try { GenericRowData row = (GenericRowData) avroDeserializer.deserialize(message); GenericRowData before = (GenericRowData) row.getField(0); GenericRowData after = (GenericRowData) row.getField(1); String op = row.getField(2).toString(); if (OP_CREATE.equals(op) || OP_READ.equals(op)) { after.setRowKind(RowKind.INSERT); out.collect(after); } else if (OP_UPDATE.equals(op)) { if (before == null) { throw new IllegalStateException(String.format(REPLICA_IDENTITY_EXCEPTION, "UPDATE")); } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } else if (OP_DELETE.equals(op)) { if (before == null) { throw new IllegalStateException(String.format(REPLICA_IDENTITY_EXCEPTION, "DELETE")); } before.setRowKind(RowKind.DELETE); out.collect(before); } else { throw new IOException(format( "Unknown \"op\" value \"%s\". The Debezium Avro message is '%s'", op, new String(message))); } } catch (Throwable t) { throw new IOException("Can't deserialize Debezium Avro message.", t); } }
Source:
<code>public static Alias getLegacyFilmAlias(String id) { <START> return new Alias(NEW_PA_BASE_ALIAS + "rt_filmnumber", id); <END> }</code><technical_language>PA_BASE_ALIAS_V2 is a bit more future-proof new</technical_language>

Target:
public static Alias getLegacyFilmAlias(String id) { return new Alias(PA_BASE_ALIAS_V2 + "rt_filmnumber", id); }
Source:
<code>public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getDeclaringClass()==IReadResolve.class) { if(goingHome) return Channel.current().getExportedObject(oid); else return proxy; } if(channel==null) throw new IllegalStateException("proxy is not connected to a channel"); if(args==null) args = EMPTY_ARRAY; Class<?> dc = method.getDeclaringClass(); if(dc ==Object.class) { try { return method.invoke(this,args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } boolean async = method.isAnnotationPresent(Asynchronous.class); RPCRequest req = new RPCRequest(oid, method, args, userProxy ? dc.getClassLoader() : null); try { if(userProxy) { if (async) channel().callAsync(req); <START> else return channel().call(req); <END> } else { if (async) req.callAsync(channel()); else return req.call(channel()); } return null; } catch (Throwable e) { for (Class exc : method.getExceptionTypes()) { if (exc.isInstance(e)) throw e; } if (e instanceof RuntimeException || e instanceof Error) throw e; throw new RemotingSystemException(e); } }</code><technical_language>is null? a channelOrFail method throwing IOException</technical_language>

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getDeclaringClass()==IReadResolve.class) { if(goingHome) return Channel.current().getExportedObject(oid); else return proxy; } if(channel==null) throw new IllegalStateException("proxy is not connected to a channel"); if(args==null) args = EMPTY_ARRAY; Class<?> dc = method.getDeclaringClass(); if(dc ==Object.class) { try { return method.invoke(this,args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } boolean async = method.isAnnotationPresent(Asynchronous.class); RPCRequest req = new RPCRequest(oid, method, args, userProxy ? dc.getClassLoader() : null); try { if(userProxy) { if (async) channelOrFail().callAsync(req); else return channelOrFail().call(req); } else { if (async) req.callAsync(channelOrFail()); else return req.call(channelOrFail()); } return null; } catch (Throwable e) { for (Class exc : method.getExceptionTypes()) { if (exc.isInstance(e)) throw e; } if (e instanceof RuntimeException || e instanceof Error) throw e; throw new RemotingSystemException(e); } }
Source:
<code>public void testCancellationDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); <START> final BlockingJobVertex blockingJobVertex = new BlockingJobVertex("testVertex"); blockingJobVertex.setInvokableClass(NoOpInvokable.class); JobGraph blockingJobGraph = new JobGraph(TEST_JOB_ID, "blockingTestJob", blockingJobVertex); <END> dispatcherGateway.submitJob(blockingJobGraph, TIMEOUT).get(); Assert.assertThat(dispatcherGateway.requestJobStatus(blockingJobGraph.getJobID(), TIMEOUT).get(), is(JobStatus.INITIALIZING)); CompletableFuture<Acknowledge> cancellationFuture = dispatcherGateway.cancelJob(blockingJobGraph.getJobID(), TIMEOUT); Assert.assertThat(dispatcherGateway.requestJobStatus(blockingJobGraph.getJobID(), TIMEOUT).get(), is(JobStatus.CANCELLING)); Assert.assertThat(cancellationFuture.isDone(), is(false)); blockingJobVertex.unblock(); cancellationFuture.get(); Assert.assertThat(dispatcherGateway.requestJobStatus(blockingJobGraph.getJobID(), TIMEOUT).get(), is(JobStatus.CANCELED)); }</code><technical_language>Duplicated code</technical_language>

Target:
public void testCancellationDuringInitialization() throws Exception { dispatcher = createAndStartDispatcher(heartbeatServices, haServices, new ExpectedJobIdJobManagerRunnerFactory(TEST_JOB_ID, createdJobManagerRunnerLatch)); jobMasterLeaderElectionService.isLeader(UUID.randomUUID()); DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class); Tuple2<JobGraph, BlockingJobVertex> blockingJobGraph = getBlockingJobGraphAndVertex(); JobID jobID = blockingJobGraph.f0.getJobID(); dispatcherGateway.submitJob(blockingJobGraph.f0, TIMEOUT).get(); assertThat(dispatcherGateway.requestJobStatus(jobID, TIMEOUT).get(), is(JobStatus.INITIALIZING)); CompletableFuture<Acknowledge> cancellationFuture = dispatcherGateway.cancelJob(jobID, TIMEOUT); assertThat(dispatcherGateway.requestJobStatus(jobID, TIMEOUT).get(), is(JobStatus.CANCELLING)); assertThat(cancellationFuture.isDone(), is(false)); blockingJobGraph.f1.unblock(); cancellationFuture.get(); assertThat(dispatcherGateway.requestJobResult(jobID, TIMEOUT).get().getApplicationStatus(), is(ApplicationStatus.CANCELED)); }
Source:
<code>private void replaceLabels(TurboIssue issue, List<String> labels) { List<String> originalLabels = issue.getLabels().stream().sorted().collect(Collectors.toList()); if (!labels.equals(originalLabels)) { List<Action> actions = getActions(originalLabels, labels); <START> List<String> resultingLabels = getResultingLabels(originalLabels, actions); <END> assert(labels.equals(resultingLabels)); ui.logic.replaceIssueLabelsUI(issue, labels); Notification undoNotification = new Notification(createInfoOcticon(), "Undo label change(s) for #" + issue.getId() + ": " + issue.getTitle(), "Undo", () -> ui.logic.replaceIssueLabelsRepo(issue, labels, originalLabels) .thenApply(success -> postReplaceLabelActions(success, issue)), () -> ui.logic.replaceIssueLabelsUI(issue, originalLabels)); ui.showNotification(undoNotification); } }</code><technical_language>methods named better. This is sort of computing a diff applying a diff sets of labels, right? Also, this part do anything? end labels result, actions</technical_language>

Target:
private void replaceLabels(TurboIssue issue, List<String> labels) { List<String> originalLabels = issue.getLabels().stream().sorted().collect(Collectors.toList()); if (!labels.equals(originalLabels)) { List<String> resultingLabels = createResultingLabelList(issue, labels); assert(labels.equals(resultingLabels)); ui.logic.replaceIssueLabelsUI(issue, resultingLabels); Notification undoNotification = new Notification(createInfoOcticon(), "Undo label change(s) for #" + issue.getId() + ": " + issue.getTitle(), "Undo", () -> ui.logic.replaceIssueLabelsRepo(issue, resultingLabels, originalLabels) .thenApply(success -> showErrorDialogOnFailure(success, issue)), () -> ui.logic.replaceIssueLabelsUI(issue, originalLabels)); ui.showNotification(undoNotification); } }
Source:
<code>private static Ordering<Ref> branchComparator(Ref headLeaf) { if (headLeaf == null) { return Ordering.from(RefComparator.INSTANCE); } final String headLeafName = headLeaf.getName(); return new Ordering<Ref>() { @Override public int compare(@Nullable Ref left, @Nullable Ref right) { boolean leftIsHead = isHead(left); boolean rightIsHead = isHead(right); <START> if (leftIsHead && !rightIsHead) { <END> return -1; } else if (rightIsHead) { return 1; } else { return 0; } } private final boolean isHead(Ref ref) { return ref != null && ref.getName().equals(headLeafName); } }.compound(RefComparator.INSTANCE); }</code><technical_language>I do this as: int l = isHead(left) ? 1 : 0; int r = isHead(right) ? 1 : 0; return r - l; is shorter. put ?: isHead method if rename sound boolean return valuey</technical_language>

Target:
private static Ordering<Ref> branchComparator(Ref headLeaf) { if (headLeaf == null) { return Ordering.from(RefComparator.INSTANCE); } final String headLeafName = headLeaf.getName(); return new Ordering<Ref>() { @Override public int compare(@Nullable Ref left, @Nullable Ref right) { int l = isHead(left) ? 1 : 0; int r = isHead(right) ? 1 : 0; return l - r; } private final boolean isHead(Ref ref) { return ref != null && ref.getName().equals(headLeafName); } }.compound(RefComparator.INSTANCE); }
Source:
<code>public static List<Cookie> parseCookieHeader(String host, String cookieHeaderValue) { <START> String cookies_string = cookieHeaderValue; <END> if (StringUtils.isEmpty(cookies_string)){ return Collections.emptyList(); } String[] cookies = cookies_string.split(";"); if (cookies.length==0){ return Collections.emptyList(); }else{ List<Cookie> cookiesList = new ArrayList<Cookie>(); for (String cookie : cookies){ String[] parts = cookie.split("="); if (parts.length==1) { cookiesList.add(new Cookie(host,parts[0].trim(),"")); }else{ cookiesList.add(new Cookie(host,parts[0].trim(),parts[1].trim())); } } return cookiesList; } }</code><technical_language>This variable removed, cookieHeaderValue directly</technical_language>

Target:
static List<Cookie> parseCookieHeader(String host, String cookieHeaderValue) { if (StringUtils.isEmpty(cookieHeaderValue)){ return Collections.emptyList(); } String[] cookies = cookieHeaderValue.split(";"); List<Cookie> cookiesList = new ArrayList<Cookie>(); for (String cookie : cookies){ String[] parts = cookie.split("="); if (parts.length==1) { cookiesList.add(new Cookie(host,parts[0].trim(),"")); }else{ cookiesList.add(new Cookie(host,parts[0].trim(),parts[1].trim())); } } return cookiesList; }
Source:
<code>public int compareTo(long thisSize, long thatSize, ResourceUnit thatUnit) { if (thatUnit instanceof MemoryUnit) { <START> return Long.signum(convert(thisSize, (MemoryUnit) thatUnit) - thatSize); <END> } else { throw new IllegalArgumentException(); } }</code><technical_language>convert is misused here, contract. a test? :smiley:</technical_language>

Target:
public int compareTo(long thisSize, long thatSize, ResourceUnit thatUnit) { if (thatUnit instanceof MemoryUnit) { MemoryUnit mThatUnit = (MemoryUnit) thatUnit; if (index < mThatUnit.index) { try { return Long.signum(thisSize - convert(thatSize, mThatUnit)); } catch (ArithmeticException e) { return Long.signum(mThatUnit.convert(thisSize, this) - thatSize); } } else { try { return Long.signum(mThatUnit.convert(thisSize, this) - thatSize); } catch (ArithmeticException e) { return Long.signum(thisSize - convert(thatSize, mThatUnit)); } } } else { throw new IllegalArgumentException(); } }
Source:
<code>public void setValueToRedis() throws IOException { Path projectDir = folder.newFolder().toPath(); addWorkflow(projectDir, "acceptance/params/set.dig"); Path config = projectDir.resolve("config"); Files.write(config, asList( "param_server.type=redis", "param_server.host=" + DIGDAG_TEST_REDIS )); CommandStatus status = main("run", "-o", folder.newFolder().getAbsolutePath(), "--config", config.toString(), "--project", projectDir.toString(), projectDir.resolve("set.dig").toString() ); assertCommandStatus(status); long key1_ttl = redisClient.ttl("0:key1"); long key2_ttl = redisClient.ttl("0:key2"); assertTrue(key1_ttl < TTL_90_DAYS_PLUS_1SEC && key1_ttl > TTL_89_DAYS); assertTrue(key2_ttl < TTL_90_DAYS_PLUS_1SEC && key2_ttl > TTL_89_DAYS); <START> <END> assertThat(redisClient.get("0:key1"), is("{\"value_type\":0,\"value\":{\"value\":\"value1\"}}")); assertThat(redisClient.get("0:key2"), is("{\"value_type\":0,\"value\":{\"value\":\"value2\"}}")); }</code><technical_language>Basic question. compare ttl < TTL_90_DAYS_PLUS_1SEC ttl <= TTL_90_DAYS</technical_language>

Target:
public void setValueToRedis() throws IOException { Path projectDir = folder.newFolder().toPath(); addWorkflow(projectDir, "acceptance/params/set.dig"); Path config = projectDir.resolve("config"); Files.write(config, asList( "param_server.type=redis", "param_server.host=" + DIGDAG_TEST_REDIS )); CommandStatus status = main("run", "-o", folder.newFolder().getAbsolutePath(), "--config", config.toString(), "--project", projectDir.toString(), projectDir.resolve("set.dig").toString() ); assertCommandStatus(status); long key1_ttl = redisClient.ttl("0:key1"); long key2_ttl = redisClient.ttl("0:key2"); assertTrue(key1_ttl <= TTL_90_DAYS && key1_ttl > TTL_89_DAYS); assertTrue(key2_ttl <= TTL_90_DAYS && key2_ttl > TTL_89_DAYS); assertThat(redisClient.get("0:key1"), is("{\"value_type\":0,\"value\":{\"value\":\"value1\"}}")); assertThat(redisClient.get("0:key2"), is("{\"value_type\":0,\"value\":{\"value\":\"value2\"}}")); }
Source:
<code>public final void start(@Nullable BundleContext context) throws Exception { super.start(context); if (ACTIVATORS.containsValue(this)) { <START> logError("Duplicate Activator ID found."); END> } ACTIVATORS.put(this.getPluginId(), this); startActions(); }</code><technical_language>please add activator ID in error message a description of conflict</technical_language>

Target:
public final void start(@Nullable BundleContext context) throws Exception { super.start(context); String id = this.getPluginId(); if (ACTIVATORS.containsKey(id)) { logError("Duplicate Activator ID : " + id); } ACTIVATORS.put(id, this); startActions(); }
Source:
<code>private List<String> initCommand(){ List<String> command = new ArrayList<String>(); command.add(cmd); command.add("install"); if (acceptLicense) { command.add("--acceptLicense"); } else { command.add("--viewLicenseAgreement"); } if (to != null) { command.add("--to=" + to); } if (whenFileExists != null) { command.add("--when-file-exists=" + whenFileExists); } if (directoryPath != null) { command.add("--location=" + directoryPath); } if (downloadOnly != null) { <START> command.add("--downloadOnly=" + downloadOnly); <END> } if (offlineOnly) { command.add("--offlineOnly"); } return command; }</code><technical_language>I this means featureManager instead of installUtility - is right? automatically get dependencies installUtility</technical_language>

Target:
private List<String> initCommand(){ List<String> command = new ArrayList<String>(); command.add(cmd); command.add("install"); if (acceptLicense) { command.add("--acceptLicense"); } else { command.add("--viewLicenseAgreement"); } if (to != null) { command.add("--to=" + to); } if (from != null) { command.add("--from=" + from); } return command; }
Source:
<code>public static Integer jsonLength(Object input) { final PathContext context = (PathContext) input; final Integer result; try { Object value = context.pathReturned; if (value == null) { result = null; } else { if (value instanceof Collection) { result = ((Collection) value).size(); } else if (value instanceof Map) { result = ((LinkedHashMap) value).size(); } else if (isScalarObject(value)) { result = 1; } else { <START> result = 0; <END> } } } catch (Exception ex) { throw RESOURCE.unknownObjectOfJsonLength( input.toString()).ex(); } return result; }</code><technical_language>context carries error (typically user passes a "strict" jsonpath expression). add a fail-fast condition exclude that. E.g. java if (context.exc != null) { throw toUnchecked(context.exc); } try { ..</technical_language>

Target:
public static Integer jsonLength(Object input) { final Integer result; final Object value; try { if (isJsonPathContext(input)) { PathContext context = (PathContext) input; if (context.exc != null) { throw toUnchecked(context.exc); } value = context.pathReturned; } else { value = input; } if (value == null) { result = null; } else { if (value instanceof Collection) { result = ((Collection) value).size(); } else if (value instanceof Map) { result = ((LinkedHashMap) value).size(); } else if (isScalarObject(value)) { result = 1; } else { result = 0; } } } catch (Exception ex) { throw RESOURCE.unknownContextOfJsonLength( input.toString()).ex(); } return result; }