auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Object invokeParser(InputStream inputStream, Function<io.crate.protocols.postgres.antlr.v4.PgArrayParser, ParserRuleContext> parseFunction, Function<byte[], Object> convert) { try { var lexer = new PgArrayLexer(CharStreams.fromStream( inputStream, Charset.forName("UTF-8"))); var tokenStream = new CommonTokenStream(lexer); var parser = new io.crate.protocols.postgres.antlr.v4.PgArrayParser(tokenStream); lexer.removeErrorListeners(); lexer.addErrorListener(ERROR_LISTENER); parser.removeErrorListeners(); parser.addErrorListener(ERROR_LISTENER); ParserRuleContext tree; try { parser.getInterpreter().setPredictionMode(PredictionMode.SLL); tree = parseFunction.apply(parser); } catch (ParseCancellationException ex) { tokenStream.seek(0); parser.reset(); parser.getInterpreter().setPredictionMode(PredictionMode.LL); tree = parseFunction.apply(parser); } return new PgArrayASTVisitor(convert).visit(tree); } catch (StackOverflowError e) { throw new PgArrayParsingException("stack overflow while parsing: " + e.getLocalizedMessage()); } catch (IOException e) { return new IllegalArgumentException(e); } }

Target:
private Object invokeParser(InputStream inputStream, Function<io.crate.protocols.postgres.antlr.v4.PgArrayParser, ParserRuleContext> parseFunction, Function<byte[], Object> convert) { try { var lexer = new PgArrayLexer(CharStreams.fromStream( inputStream, StandardCharsets.UTF_8)); var tokenStream = new CommonTokenStream(lexer); var parser = new io.crate.protocols.postgres.antlr.v4.PgArrayParser(tokenStream); lexer.removeErrorListeners(); lexer.addErrorListener(ERROR_LISTENER); parser.removeErrorListeners(); parser.addErrorListener(ERROR_LISTENER); ParserRuleContext tree; try { parser.getInterpreter().setPredictionMode(PredictionMode.SLL); tree = parseFunction.apply(parser); } catch (ParseCancellationException ex) { tokenStream.seek(0); parser.reset(); parser.getInterpreter().setPredictionMode(PredictionMode.LL); tree = parseFunction.apply(parser); } return new PgArrayASTVisitor(convert).visit(tree); } catch (StackOverflowError e) { throw new PgArrayParsingException("stack overflow while parsing: " + e.getLocalizedMessage()); } catch (IOException e) { return new IllegalArgumentException(e); } }
Source:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); if (context.isRegisterTransformers()) { JSFResourceDefinition.registerTransformers(subsystem); } }

Target:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); }
Source:
public void onIndexPageWithResourcesFromCdn() { ContentSecurityPolicyHeaderWriter writer = new ContentSecurityPolicyHeaderWriter( true, false, bool(), SiteUrl.PUBLIC_URL, H2_CONSOLE_PROPERTIES ); String[] directives = writer.constructDirectives("/").split(";"); assertThat(directives) .contains( "default-src 'none'", "img-src <LINK_3> <LINK_4>", "font-src <LINK_2>", "report-uri <LINK_0>" ) .contains( "style-src " + "'report-sample' " + "<LINK_3> " + "<LINK_4> " + "<LINK_2>" ) .contains( "script-src " + "'report-sample' " + "'unsafe-inline' " + "<LINK_4> " + "<LINK_2> " + "<LINK_1>" ) .hasSize(NUMBER_OF_DIRECTIVES_ON_STANDARD_PAGES); }

Target:
public void onIndexPageWithResourcesFromCdn() { ContentSecurityPolicyHeaderWriter writer = new ContentSecurityPolicyHeaderWriter( true, false, bool(), SiteUrl.PUBLIC_URL, H2_CONSOLE_PATH ); String[] directives = writer.constructDirectives("/").split(";"); assertThat(directives) .contains( "default-src 'none'", "img-src <LINK_3> <LINK_4>", "font-src <LINK_2>", "report-uri <LINK_0>" ) .contains( "style-src " + "'report-sample' " + "<LINK_3> " + "<LINK_4> " + "<LINK_2>" ) .contains( "script-src " + "'report-sample' " + "'unsafe-inline' " + "<LINK_4> " + "<LINK_2> " + "<LINK_1>" ) .hasSize(NUMBER_OF_DIRECTIVES_ON_STANDARD_PAGES); }
Source:
private Exception createTimeoutException(Thread thread) { StackTraceElement[] stackTrace = thread.getStackTrace(); final Thread stuckThread = fLookForStuckThread ? getStuckThread(thread) : null; Exception currThreadException = new TestFailedOnTimeoutException(String.format( "test timed out after %d %s", fTimeout, fTimeUnit.name().toLowerCase())); if (stackTrace != null) { currThreadException.setStackTrace(stackTrace); thread.interrupt(); } if (stuckThread != null) { Exception stuckThreadException = new Exception ("Appears to be stuck in thread " + stuckThread.getName()); stuckThreadException.setStackTrace(getStackTrace(stuckThread)); return new MultipleFailureException (Arrays.<Throwable>asList(currThreadException, stuckThreadException)); } else { return currThreadException; } }

Target:
private Exception createTimeoutException(Thread thread) { StackTraceElement[] stackTrace = thread.getStackTrace(); final Thread stuckThread = fLookForStuckThread ? getStuckThread(thread) : null; Exception currThreadException = new TestTimedOutException(fTimeout, fTimeUnit); if (stackTrace != null) { currThreadException.setStackTrace(stackTrace); thread.interrupt(); } if (stuckThread != null) { Exception stuckThreadException = new Exception ("Appears to be stuck in thread " + stuckThread.getName()); stuckThreadException.setStackTrace(getStackTrace(stuckThread)); return new MultipleFailureException (Arrays.<Throwable>asList(currThreadException, stuckThreadException)); } else { return currThreadException; } }
Source:
protected Tag getVersion(Tool tool) { Tag tag = new Tag(); tag.setCwlPath("/Dockstore.cwl"); tag.setDockerfilePath("/Dockerfile"); tag.setAutomated(false); tag.setWdlPath("/Dockstore.wdl"); tag.setReferenceType(Version.ReferenceType.TAG); tag.setLastBuilt(new Date()); return tag; }

Target:
protected Tag getVersion(Tool tool) { Tag tag = new Tag(); tag.setCwlPath("/Dockstore.cwl"); tag.setDockerfilePath("/Dockerfile"); tag.setAutomated(false); tag.setWdlPath("/Dockstore.wdl"); tag.setReferenceType(Version.ReferenceType.TAG); return tag; }
Source:
public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { FastReaderBuilder localFastReader = new FastReaderBuilder(this); this.fastReaderBuilder = localFastReader; return localFastReader; } else { return this.fastReaderBuilder; } }

Target:
public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { fastReaderBuilder = new FastReaderBuilder(this); } return this.fastReaderBuilder; }
Source:
void setFadeEnabled(boolean enabled) { fadeEnabled = enabled; pageFragment.getWebView().postDelayed(this::update, DELAY_UPDATE_MS); }

Target:
void setFadeEnabled(boolean enabled) { fadeEnabled = enabled; update(); }
Source:
protected void scheduleFlush(String encodedRegionName, List<byte[]> families) { RegionServerServices services = this.abortable; HRegion r = (HRegion) services.getRegion(encodedRegionName); if (r == null) { LOG.warn("Failed to schedule flush of {}, because it is not online on us", encodedRegionName); return; } FlushRequester requester = services.getFlushRequester(); if (requester == null) { LOG.warn("Failed to schedule flush of {}, region={}, because FlushRequester is null", encodedRegionName, r); return; } requester.requestFlush(r, false, families, FlushLifeCycleTracker.DUMMY); }

Target:
protected void scheduleFlush(String encodedRegionName, List<byte[]> families) { RegionServerServices services = this.abortable; HRegion r = (HRegion) services.getRegion(encodedRegionName); if (r == null) { LOG.warn("Failed to schedule flush of {}, because it is not online on us", encodedRegionName); return; } FlushRequester requester = services.getFlushRequester(); if (requester == null) { LOG.warn("Failed to schedule flush of {}, region={}, because FlushRequester is null", encodedRegionName, r); return; } requester.requestFlush(r, families, FlushLifeCycleTracker.DUMMY); }
Source:
private void makeCachedRequestWithCredsId(String credsId) throws IOException { GitHubServerConfig config = new GitHubServerConfig(credsId); config.setApiUrl(github.serverConfig().getApiUrl()); config.setClientCacheSize(1); GitHub gitHub = new GitHubLoginFunction().apply(config); gitHub.getMyself(); }

Target:
private void makeCachedRequestWithCredsId(String credsId) throws IOException { GitHubServerConfig config = new GitHubServerConfig(credsId); config.setApiUrl(github.serverConfig().getApiUrl()); config.setClientCacheSize(1); GitHub gitHub = GitHubServerConfig.loginToGithub().apply(config); gitHub.getMyself(); }
Source:
public synchronized void send(DatastreamEventRecord record) throws DatastreamException { if (_shutdownRequested) { throw new IllegalStateException("send() is not allowed on a shutdown producer"); } validateEventRecord(record); try { _transportProvider.send(record); _latestCheckpoints.get(record.getDatastreamTask()).put(record.getPartition(), record.getCheckpoint()); _pendingCheckpoint = true; } catch (TransportException e) { throw new DatastreamException("Failed to send: " + record, e); } }

Target:
public synchronized void send(DatastreamEventRecord record) { if (_shutdownRequested) { throw new IllegalStateException("send() is not allowed on a shutdown producer"); } validateEventRecord(record); try { _transportProvider.send(record); _latestCheckpoints.get(record.getDatastreamTask()).put(record.getPartition(), record.getCheckpoint()); _pendingCheckpoint = true; } catch (TransportException e) { throw new RuntimeException("Failed to send: " + record, e); } }
Source:
public static DataType<?> getCommonType(DataType<?> firstType, DataType<?> secondType) { TypeCompatibility compatibility = compatibility(firstType, secondType); if (!compatibility.isCompatible()) { return null; } return compatibility.getCommonType(); }

Target:
public static DataType<?> getCommonType(DataType<?> firstType, DataType<?> secondType) { return compatibility(firstType, secondType); }
Source:
private Map<URL, URL> findExportedResources(Module dependencyModule, Map<String, Map<URL, URL>> exportedResourcesCache) { if (exportedResourcesCache.containsKey(dependencyModule)) { return exportedResourcesCache.get(dependencyModule.getName()); } Set<URL> beanXmls = findExportedResource(dependencyModule, META_INF_BEANS_XML); if (beanXmls.isEmpty()) { exportedResourcesCache.put(dependencyModule.getName(), Collections.emptyMap()); return Collections.emptyMap(); } Set<URL> indexes = findExportedResource(dependencyModule, META_INF_JANDEX_IDX); Map<URL, URL> ret = new HashMap<>(); for (URL beansXml : beanXmls) { String urlBase = beansXml.toString().substring(0, beansXml.toString().length() - META_INF_BEANS_XML.length()); URL idx = null; for (URL index : indexes) { if (index.toString().startsWith(urlBase)) { idx = index; break; } } ret.put(beansXml, idx); } exportedResourcesCache.put(dependencyModule.getName(), ret); return ret; }

Target:
private Map<URL, URL> findExportedResources(Module dependencyModule, Map<String, Map<URL, URL>> exportedResourcesCache) { if (exportedResourcesCache.containsKey(dependencyModule.getName())) { return exportedResourcesCache.get(dependencyModule.getName()); } Set<URL> beanXmls = findExportedResource(dependencyModule, META_INF_BEANS_XML); if (beanXmls.isEmpty()) { exportedResourcesCache.put(dependencyModule.getName(), Collections.emptyMap()); return Collections.emptyMap(); } Set<URL> indexes = findExportedResource(dependencyModule, META_INF_JANDEX_IDX); Map<URL, URL> ret = new HashMap<>(); for (URL beansXml : beanXmls) { String urlBase = beansXml.toString().substring(0, beansXml.toString().length() - META_INF_BEANS_XML.length()); URL idx = null; for (URL index : indexes) { if (index.toString().startsWith(urlBase)) { idx = index; break; } } ret.put(beansXml, idx); } exportedResourcesCache.put(dependencyModule.getName(), ret); return ret; }
Source:
private String getDatabase(final Query query) { String db = query.getDatabase(); return db == null ? this.database : db; }

Target:
private String getDatabase(final Query query) { String db = query.getDatabase(); if (db == null) { return this.database; } return db; }
Source:
private Map<String, List<Entry<T>>> copy(final Map<String, List<Entry<T>>> original) { final Map<String, List<Entry<T>>> copy = new HashMap<>(); original.forEach((key, value) -> copy.put(key, new CopyOnWriteArrayList<>(value))); return copy; }

Target:
private Map<String, List<Entry<T>>> copy(final Map<String, List<Entry<T>>> original) { final Map<String, List<Entry<T>>> copy = new HashMap<>(original.size()); original.forEach((key, value) -> copy.put(key, new CopyOnWriteArrayList<>(value))); return copy; }
Source:
private void executeStartOperation(final PlanOperation startOp) { final String planContextId = startOp.getEvalId().get(); final Optional<ActiveContext> context = executingPlan.getAddedWorkerContext(planContextId); if (context.isPresent()) { final String contextId = context.get().getId(); LOG.log(Level.FINE, "START: worker {0}", contextId); asyncDolphinDriver.get().getSecondContextActiveHandlerForWorker(true).onNext(context.get()); executingPlan.putWorkerTaskControlOp(contextId, startOp); } else { throw new RuntimeException("There's no worker evaluator to start"); } }

Target:
private void executeStartOperation(final PlanOperation startOp) { final String planContextId = startOp.getEvalId().get(); final Optional<ActiveContext> context = executingPlan.getAddedWorkerContext(planContextId); if (context.isPresent()) { final String contextId = context.get().getId(); LOG.log(Level.FINE, "START: worker {0}", contextId); executingPlan.putWorkerTaskControlOp(contextId, startOp); asyncDolphinDriver.get().getSecondContextActiveHandlerForWorker(true).onNext(context.get()); } else { throw new RuntimeException("There's no worker evaluator to start"); } }
Source:
public AnalysisResult runCheckers(ImmutableList<AnalysisResult> knownResultsSoFar, AnalysisDatabase database, MutableTypeInformation mutableTypeInformation, AnalysisInProgress analysisInProgress) { Map<IsImmutable, Integer> results = newHashMap(); Collection<MutableReasonDetail> reasons = newArrayList(); Collection<AnalysisError> errors = newArrayList(); boolean isClassSelfReferenced=false; Iterable<AsmMutabilityChecker> checkers = factory.createInstances( database, verifierFactory, mutableTypeInformation, analysisInProgress); CheckerRunner checkerRunner = checkerRunnerFactory.createRunner(); for (AsmMutabilityChecker checker : checkers) { if(checker instanceof CollectionWithMutableElementTypeToFieldChecker) { checker.setIsClassSelfReferenced(isClassSelfReferenced); } CheckerResult checkerResult = checkerRunner.run(checker, toAnalyse, knownResultsSoFar); if(checker instanceof MutableTypeToFieldChecker) { isClassSelfReferenced = checker.isClassSelfReferenced(); } results.put(checkerResult.isImmutable, getNewCount(results, checkerResult.isImmutable)); reasons.addAll(checkerResult.reasons); errors.addAll(checkerResult.errors); } IsImmutable isImmutable = new ResultCalculator().calculateImmutableStatus(results); return AnalysisResult.analysisResult(toAnalyse, isImmutable, reasons, errors); }

Target:
public AnalysisResult runCheckers(ImmutableList<AnalysisResult> knownResultsSoFar, AnalysisDatabase database, MutableTypeInformation mutableTypeInformation, AnalysisInProgress analysisInProgress) { Map<IsImmutable, Integer> results = newHashMap(); Collection<MutableReasonDetail> reasons = newArrayList(); Collection<AnalysisError> errors = newArrayList(); Iterable<AsmMutabilityChecker> checkers = factory.createInstances( database, verifierFactory, mutableTypeInformation, analysisInProgress); CheckerRunner checkerRunner = checkerRunnerFactory.createRunner(); for (AsmMutabilityChecker checker : checkers) { CheckerResult checkerResult = checkerRunner.run(checker, toAnalyse, knownResultsSoFar); results.put(checkerResult.isImmutable, getNewCount(results, checkerResult.isImmutable)); reasons.addAll(checkerResult.reasons); errors.addAll(checkerResult.errors); } IsImmutable isImmutable = new ResultCalculator().calculateImmutableStatus(results); return AnalysisResult.analysisResult(toAnalyse, isImmutable, reasons, errors); }
Source:
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.get().getKeyType().equals(RSA) || key.get().getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(EC) || key.get().getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key.get(), cryptographyServiceClient); } else if (key.get().getKeyType().equals(OCT)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key.get(), cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.get().getKeyType().toString()))); } }

Target:
private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } if (key.getKeyType().equals(RSA) || key.getKeyType().equals(RSA_HSM)) { localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(EC) || key.getKeyType().equals(EC_HSM)) { localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); } else if (key.getKeyType().equals(OCT)) { localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); } else { throw logger.logExceptionAsError(new IllegalArgumentException(String.format( "The Json Web Key Type: %s is not supported.", key.getKeyType().toString()))); } }
Source:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { ; } return val; }

Target:
public static final int compare(MemorySegment seg1, MemorySegment seg2, int offset1, int offset2, int len) { final byte[] b1 = seg1.memory; final byte[] b2 = seg2.memory; int val = 0; for (int pos = 0; pos < len && (val = (b1[offset1 + pos] & 0xff) - (b2[offset2 + pos] & 0xff)) == 0; pos++) { } return val; }
Source:
public int hashCode() { return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), ttl, getPushTitle(), pushBody); }

Target:
public int hashCode() { return Objects.hash(getUsername(), getPolicy(), getContext(), getTitle(), getTTL(), getPushTitle(), getPushBody()); }
Source:
public void onMatch(RelOptRuleCall call) { SingleRel single = call.rel(0); RelNode emptyValues = call.builder().push(single).empty().build(); RelNode result = emptyValues.copy(single.getTraitSet(), Collections.emptyList()); call.transformTo(result); }

Target:
public void onMatch(RelOptRuleCall call) { SingleRel singleRel = call.rel(0); RelNode emptyValues = call.builder().push(singleRel).empty().build(); RelTraitSet traits = singleRel.getTraitSet(); if (emptyValues.getConvention() != null) { traits = traits.replace(emptyValues.getConvention()); } emptyValues = emptyValues.copy(traits, Collections.emptyList()); call.transformTo(emptyValues); }
Source:
public String getString(String key) throws JSONException { Object object = this.get(key); return object.toString(); }

Target:
public String getString(String key) throws JSONException { return this.get(key).toString(); }
Source:
private static boolean isPositionWithin(final ContentPosition position, final Box box) { return position.getOffset() >= box.getStartOffset() && position.getOffset() <= box.getEndOffset(); }

Target:
private static boolean isPositionWithin(final ContentPosition position, final Box box) { return position.isAfterOrEquals(new ContentPosition(box.getNode(), box.getStartOffset())) && position.isBeforeOrEquals(new ContentPosition(box.getNode(), box.getEndOffset())); }
Source:
private static Object evaluate(TokenKind op, Object value, Location loc) throws EvalException, InterruptedException { switch (op) { case NOT: return !EvalUtils.toBoolean(value); case MINUS: if (!(value instanceof Integer)) { throw new EvalException( loc, String.format( "unsupported operand type for -: '%s'", EvalUtils.getDataTypeName(value))); } try { return Math.negateExact((Integer) value); } catch (ArithmeticException e) { throw new EvalException(loc, e.getMessage()); } case TILDE: if (!(value instanceof Integer)) { throw new EvalException( loc, String.format( "unsupported operand type for ~: '%s'", EvalUtils.getDataTypeName(value))); } return ~((Integer) value); default: throw new AssertionError("Unsupported unary operator: " + op); } }

Target:
private static Object evaluate(TokenKind op, Object value, Location loc) throws EvalException, InterruptedException { switch (op) { case NOT: return !EvalUtils.toBoolean(value); case MINUS: if (value instanceof Integer) { try { return Math.negateExact((Integer) value); } catch (ArithmeticException e) { throw new EvalException(loc, e.getMessage()); } } break; case PLUS: if (value instanceof Integer) { return value; } break; case TILDE: if (value instanceof Integer) { return ~((Integer) value); } break; default: } throw new EvalException( loc, String.format( "unsupported unary operation: %s%s", op, EvalUtils.getDataTypeName(value))); }
Source:
public String toString() { switch (this) { case APPS: return "Apps"; case ENGINES: return "Engines"; default: throw new IllegalArgumentException(); } }

Target:
public String toString() { return this.displayName; }
Source:
public CPUStat getCPUStat() { return new CPUStat(); }

Target:
public CPUStat getCPUStat() { return _cpuStat; }
Source:
private Void dropTablesWithPrefix(String prefix) { String namespacedPrefix = NAMESPACE.getName() + "." + prefix + "__"; Set<TableReference> tablesToDrop = Sets.newHashSet(); for (TableReference tableRef : kvs.getAllTableNames()) { if (tableRef.getQualifiedName().startsWith(namespacedPrefix)) { tablesToDrop.add(tableRef); } } kvs.dropTables(tablesToDrop); return null; }

Target:
private Void dropTablesWithPrefix(String prefix) { String namespacedPrefix = NAMESPACE.getName() + "." + prefix + "__"; Set<TableReference> tablesToDrop = kvs.getAllTableNames().stream() .filter(tableRef -> tableRef.getQualifiedName().startsWith(namespacedPrefix)) .collect(Collectors.toSet()); kvs.dropTables(tablesToDrop); return null; }
Source:
public static CardinalitySize getEstimatedCardinality( String dimension, Class<?> cls, EntityDictionary entityDictionary ) { if (entityDictionary.isRelation(cls, dimension)) { Cardinality annotation = entityDictionary.getAttributeOrRelationAnnotation( cls, Cardinality.class, dimension ); if (annotation != null) { return annotation.size(); } } Cardinality annotation = entityDictionary .getAttributeOrRelationAnnotation(cls, Cardinality.class, dimension); return annotation == null ? getDefaultCardinality() : annotation.size(); }

Target:
public static CardinalitySize getEstimatedCardinality( String dimension, Class<?> cls, EntityDictionary entityDictionary ) { if (entityDictionary.isRelation(cls, dimension)) { Cardinality annotation = entityDictionary.getAnnotation( entityDictionary.getType(cls, dimension), Cardinality.class ); if (annotation != null) { return annotation.size(); } } Cardinality annotation = entityDictionary .getAttributeOrRelationAnnotation(cls, Cardinality.class, dimension); return annotation == null ? getDefaultCardinality() : annotation.size(); }
Source:
public int read(ByteBuffer buff) throws IOException { int read = 0; if (this.appPeerBuffer.position() == 0) { this.channel.read(this.packatPeerBuffer); if (this.packatPeerBuffer.position() == 0) { return read; } this.packatPeerBuffer.flip(); boolean retry = true; while (retry) { SSLEngineResult result = this.engine.unwrap(this.packatPeerBuffer, this.appPeerBuffer); switch (result.getStatus()) { case BUFFER_OVERFLOW: putBuffer(buff); read += result.bytesProduced(); retry = false; break; case BUFFER_UNDERFLOW: read += result.bytesProduced(); retry = false; break; default: if (HandshakeStatus.NEED_TASK.equals(result.getHandshakeStatus()) || !this.appPeerBuffer.hasRemaining()) { retry = false; } read += result.bytesProduced(); } } this.packatPeerBuffer.compact(); } putBuffer(buff); return read; }

Target:
public int read(ByteBuffer buff) throws IOException { int read = 0; if (this.appPeerBuffer.position() == 0) { this.channel.read(this.packatPeerBuffer); if (this.packatPeerBuffer.position() == 0) { return read; } this.packatPeerBuffer.flip(); boolean retry = true; while (retry) { SSLEngineResult result = this.engine.unwrap(this.packatPeerBuffer, this.appPeerBuffer); switch (result.getStatus()) { case BUFFER_OVERFLOW: putBuffer(buff); case BUFFER_UNDERFLOW: read += result.bytesProduced(); retry = false; break; default: if (HandshakeStatus.NEED_TASK.equals(result.getHandshakeStatus()) || !this.appPeerBuffer.hasRemaining()) { retry = false; } read += result.bytesProduced(); } } this.packatPeerBuffer.compact(); } putBuffer(buff); return read; }
Source:
public void testRegisterClusterListenerDuplicates() { reset(); TestClusterListener clusterListener = new TestClusterListener(); _state.registerClusterListener(clusterListener); _state.registerClusterListener(clusterListener); _state.listenToCluster(CLUSTER1_CLUSTER_NAME, new NullStateListenerCallback()); _clusterRegistry.put(CLUSTER1_CLUSTER_NAME, new ClusterProperties(CLUSTER1_CLUSTER_NAME)); assertEquals(clusterListener.getCount(CLUSTER1_CLUSTER_NAME), 1, "expected 1 call"); }

Target:
public void testRegisterClusterListenerDuplicates() { reset(); MockClusterListener clusterListener = new MockClusterListener(); _state.registerClusterListener(clusterListener); _state.registerClusterListener(clusterListener); _state.listenToCluster(CLUSTER1_CLUSTER_NAME, new NullStateListenerCallback()); _clusterRegistry.put(CLUSTER1_CLUSTER_NAME, new ClusterProperties(CLUSTER1_CLUSTER_NAME)); assertEquals(clusterListener.getClusterAddedCount(CLUSTER1_CLUSTER_NAME), 1, "expected 1 call since duplicates are not allowed"); }
Source:
private ExportValue emptyValue() { return new JustValue("", ValueType.EMPTY, (empty) -> "--"); }

Target:
private ExportValue emptyValue() { return new JustValue("--", ValueType.EMPTY); }
Source:
protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (!shutDown || drainingBeforeShutdown) { try { final ApnsConnection<T> connection = connectionPool.getNextConnection(); T notification = retryQueue.poll(); if (notification == null && !drainingBeforeShutdown) { notification = queue.poll(); } if (notification != null) { connection.sendNotification(notification); } else { if (drainingBeforeShutdown) { for (final ApnsConnection<T> connectionToClose : connectionPool.getAll()) { connectionToClose.shutdownGracefully(); } } Thread.sleep(POLL_TIMEOUT); } } catch (InterruptedException e) { continue; } } } }); }

Target:
protected Thread createDispatchThread() { return new Thread(new Runnable() { public void run() { while (!shutDown || drainingBeforeShutdown) { try { final ApnsConnection<T> connection = connectionPool.getNextConnection(); T notification = retryQueue.poll(); if (notification == null && !drainingBeforeShutdown) { notification = queue.take(); } if (notification != null) { connection.sendNotification(notification); } else { for (final ApnsConnection<T> connectionToClose : connectionPool.getAll()) { connectionToClose.shutdownGracefully(); } } } catch (InterruptedException e) { continue; } } } }); }
Source:
public String toString() { return "BuildImageParams{" + "repository='" + repository + '\'' + ", tag='" + tag + '\'' + ", authConfigs=" + authConfigs + ", doForcePull=" + doForcePull + ", memoryLimit=" + memoryLimit + ", memorySwapLimit=" + memorySwapLimit + ", files=" + files + ", dockerfile='" + dockerfile + '\'' + ", remote='" + remote + '\'' + ", quiet=" + quiet + ", noCache=" + noCache + ", removeIntermediateContainer=" + removeIntermediateContainer + ", forceRemoveIntermediateContainers=" + forceRemoveIntermediateContainers + ", cpusetCpus=" + cpusetCpus + ", cpuPeriod=" + cpuPeriod + ", cpuQuota=" + cpuQuota + ", buildArgs=" + buildArgs + '}'; }

Target:
public String toString() { return "BuildImageParams{" + "repository='" + repository + '\'' + ", tag='" + tag + '\'' + ", authConfigs='" + authConfigs + '\'' + ", doForcePull='" + doForcePull + '\'' + ", memoryLimit='" + memoryLimit + '\'' + ", memorySwapLimit='" + memorySwapLimit + '\'' + ", files=" + files + '\'' + ", dockerfile='" + dockerfile + '\'' + ", remote='" + remote + '\'' + ", quiet='" + quiet + '\'' + ", noCache='" + noCache + '\'' + ", removeIntermediateContainer='" + removeIntermediateContainer + '\'' + ", forceRemoveIntermediateContainers='" + forceRemoveIntermediateContainers + '\'' + ", cpusetCpus='" + cpusetCpus + '\'' + ", cpuPeriod='" + cpuPeriod + '\'' + ", cpuQuota='" + cpuQuota + '\'' + ", buildArgs='" + buildArgs + '\'' + '}'; }
Source:
public void testSerializable() throws JsonProcessingException { RestoreRedundancyResultsImpl restoreRedundancyResults = new RestoreRedundancyResultsImpl(); restoreRedundancyResults.setStatusMessage("Test"); restoreRedundancyResults.setSuccess(true); restoreRedundancyResults.setTotalPrimaryTransfersCompleted(150); restoreRedundancyResults.setTotalPrimaryTransferTime(250); RegionRedundancyStatusImpl regionRedundancyStatus = new RegionRedundancyStatusImpl(); regionRedundancyStatus.setActualRedundancy(1); regionRedundancyStatus.setConfiguredRedundancy(1); regionRedundancyStatus.setRegionName("/foo"); regionRedundancyStatus.setStatus(SATISFIED); restoreRedundancyResults.addRegionResult(regionRedundancyStatus); String jsonString = geodeMapper.writeValueAsString(restoreRedundancyResults); RestoreRedundancyResultsImpl value = geodeMapper.readValue(jsonString, RestoreRedundancyResultsImpl.class); assertThat(value.getStatusMessage()).isEqualTo("Test"); assertThat(value.getSuccess()).isTrue(); }

Target:
public void testSerializable() throws JsonProcessingException { RestoreRedundancyResultsImpl restoreRedundancyResults = new RestoreRedundancyResultsImpl(); restoreRedundancyResults.setStatusMessage(TEST_STRING); restoreRedundancyResults.setSuccess(true); restoreRedundancyResults.setTotalPrimaryTransfersCompleted(150); restoreRedundancyResults.setTotalPrimaryTransferTime(250); RegionRedundancyStatusImpl regionRedundancyStatus = new RegionRedundancyStatusImpl(); regionRedundancyStatus.setActualRedundancy(1); regionRedundancyStatus.setConfiguredRedundancy(1); regionRedundancyStatus.setRegionName("/foo"); regionRedundancyStatus.setStatus(SATISFIED); restoreRedundancyResults.addRegionResult(regionRedundancyStatus); String jsonString = geodeMapper.writeValueAsString(restoreRedundancyResults); RestoreRedundancyResultsImpl value = geodeMapper.readValue(jsonString, RestoreRedundancyResultsImpl.class); assertThat(value).usingRecursiveComparison().isEqualTo(restoreRedundancyResults); }
Source:
public void toggleAvailableOffline(OCFile file, boolean isAvailableOffline) { if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT == file.getAvailableOfflineStatus()) { Snackbar snackbar = Snackbar.make( mFileActivity.findViewById(android.R.id.content), R.string.available_offline_inherited_msg, Snackbar.LENGTH_LONG ); snackbar.show(); } else { OCFile.AvailableOfflineStatus targetAvailableOfflineStatus = isAvailableOffline ? OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE : OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE; file.setAvailableOfflineStatus(targetAvailableOfflineStatus); boolean success = mFileActivity.getStorageManager().saveLocalAvailableOfflineStatus(file); if (success) { FileObserverService.observeFile( mFileActivity, file, mFileActivity.getAccount(), isAvailableOffline ); if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE == file.getAvailableOfflineStatus()) { syncFile(file); } else { cancelTransference(file); } } else { Snackbar snackbar = Snackbar.make( mFileActivity.findViewById(android.R.id.content), R.string.common_error_unknown, Snackbar.LENGTH_LONG ); snackbar.show(); } } }

Target:
public void toggleAvailableOffline(OCFile file, boolean isAvailableOffline) { if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT == file.getAvailableOfflineStatus()) { mFileActivity.showSnackMessage( mFileActivity.getString(R.string.available_offline_inherited_msg) ); } else { OCFile.AvailableOfflineStatus targetAvailableOfflineStatus = isAvailableOffline ? OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE : OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE; file.setAvailableOfflineStatus(targetAvailableOfflineStatus); boolean success = mFileActivity.getStorageManager().saveLocalAvailableOfflineStatus(file); if (success) { FileObserverService.observeFile( mFileActivity, file, mFileActivity.getAccount(), isAvailableOffline ); if (OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE == file.getAvailableOfflineStatus()) { syncFile(file); } else { cancelTransference(file); } } else { mFileActivity.showSnackMessage( mFileActivity.getString(R.string.common_error_unknown) ); } } }
Source:
private MQTTSessionState getSessionState(String clientId) { return MQTTSession.getSessionState(clientId, session.getServer().getIdentity()); }

Target:
private MQTTSessionState getSessionState(String clientId) { return session.getProtocolManager().getSessionState(clientId); }
Source:
public void createSynapseDebugEnvironment(ServerContextInformation contextInfo) { try { String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); File synapseProperties = new File(CarbonUtils.getCarbonConfigDirPath() + File.separator + "synapse" + ".properties"); Properties properties = new Properties(); InputStream inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); inputStream.close(); int event_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_EVENT_PORT)); int command_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_COMMAND_PORT)); SynapseDebugInterface debugInterface = SynapseDebugInterface.getInstance(); debugInterface.init(command_port, event_port); contextInfo.setServerDebugModeEnabled(true); contextInfo.setSynapseDebugInterface(debugInterface); SynapseDebugManager debugManager = SynapseDebugManager.getInstance(); contextInfo.setSynapseDebugManager(debugManager); log.info("Synapse debug Environment created successfully"); } catch (IOException ex) { log.error("Error while creating Synapse debug environment ", ex); } catch (InterruptedException ex) { log.error("Error while creating Synapse debug environment ", ex); } }

Target:
public void createSynapseDebugEnvironment(ServerContextInformation contextInfo) { try { File synapseProperties = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "synapse.properties").toFile(); Properties properties = new Properties(); InputStream inputStream = new FileInputStream(synapseProperties); properties.load(inputStream); inputStream.close(); int event_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_EVENT_PORT)); int command_port = Integer.parseInt(properties.getProperty(ServiceBusConstants.ESB_DEBUG_COMMAND_PORT)); SynapseDebugInterface debugInterface = SynapseDebugInterface.getInstance(); debugInterface.init(command_port, event_port); contextInfo.setServerDebugModeEnabled(true); contextInfo.setSynapseDebugInterface(debugInterface); SynapseDebugManager debugManager = SynapseDebugManager.getInstance(); contextInfo.setSynapseDebugManager(debugManager); log.info("Synapse debug Environment created successfully"); } catch (IOException ex) { log.error("Error while creating Synapse debug environment ", ex); } catch (InterruptedException ex) { log.error("Error while creating Synapse debug environment ", ex); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAnalyticsListener.trackLoginMagicLinkOpened(); Intent intent = new Intent(this, WPMainActivity.class); intent.setAction(getIntent().getAction()); intent.setData(getIntent().getData()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); mLoginAnalyticsListener.trackLoginMagicLinkOpened(); Intent intent = new Intent(this, WPMainActivity.class); intent.setAction(getIntent().getAction()); intent.setData(getIntent().getData()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish(); }
Source:
public void registerAttributes(ManagementResourceRegistration registry) { super.registerAttributes(registry); registerPatchingAttributes(registry); final StandardResourceDescriptionResolver resolver = new StandardResourceDescriptionResolver("patching.patch-stream", RESOURCE_NAME, PatchResourceDefinition.class.getClassLoader()); registry.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement("patch-stream"), resolver) { @Override public void registerAttributes(final ManagementResourceRegistration resource) { super.registerAttributes(resource); registerPatchingAttributes(resource); resource.setRuntimeOnly(true); } @Override public void registerOperations(ManagementResourceRegistration registry) { PatchResourceDefinition.this.registerPatchingOperations(registry, false); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return sensitivity; } }); registry.setRuntimeOnly(true); }

Target:
public void registerAttributes(ManagementResourceRegistration registry) { super.registerAttributes(registry); registerPatchingAttributes(registry); final StandardResourceDescriptionResolver resolver = new StandardResourceDescriptionResolver("patching.patch-stream", RESOURCE_NAME, PatchResourceDefinition.class.getClassLoader()); registry.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement("patch-stream"), resolver) { @Override public void registerAttributes(final ManagementResourceRegistration resource) { super.registerAttributes(resource); registerPatchingAttributes(resource); } @Override public void registerOperations(ManagementResourceRegistration registry) { PatchResourceDefinition.this.registerPatchingOperations(registry, false); } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return sensitivity; } }); }
Source:
public RestHighLevelClient create() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(args.esUser, args.esPassword)); return new RestHighLevelClient( RestClient.builder(new HttpHost(args.esHostname, args.esPort, "http")) .setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }) .setRequestConfigCallback(new RequestConfigCallback() { @Override public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) { return requestConfigBuilder .setConnectTimeout(args.esConnectTimeout) .setSocketTimeout(args.esSocketTimeout); } }) ); }

Target:
public RestHighLevelClient create() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(args.esUser, args.esPassword)); return new RestHighLevelClient( RestClient.builder(new HttpHost(args.esHostname, args.esPort, "http")) .setHttpClientConfigCallback( (HttpAsyncClientBuilder httpClientBuilder) -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .setRequestConfigCallback( (RequestConfig.Builder requestConfigBuilder) -> requestConfigBuilder .setConnectTimeout(args.esConnectTimeout) .setSocketTimeout(args.esSocketTimeout)) ); }
Source:
private XSSFSheet getSheet() { if(sheet==null) { workbook = new XSSFWorkbook(); sheet = workbook.createSheet(); } return sheet; }

Target:
private XSSFSheet getSheet() { XSSFSheet sheet = null; try { sheet = getWorkbook().getSheetAt(0); } catch (InvalidFormatException ife) { } catch (IOException ioe) { } return sheet; }
Source:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.error("Interrupted when trying to buffer data! Dropping data"); return false; } }

Target:
protected boolean addToBuffer(T persistenceItem) { try { return buffer.offer(persistenceItem, BUFFER_OFFER_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.warn("Interrupted when trying to buffer data! Dropping data"); return false; } }
Source:
private PrivateKeyEntry getPrivateKeyEntry() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); KeyStore.PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StoreUtil.getInstance().getPrivateKeyAlias(); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_SECRET_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("javax.net.ssl.keyStorePassword is not a defined system property."); } } else { LOG.error(NhincConstants.CLIENT_KEY_ALIAS + " is not a defined system property."); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }

Target:
private PrivateKeyEntry getPrivateKeyEntry() throws CertificateManagerException { LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin"); KeyStore.PrivateKeyEntry pkEntry = null; final String clientkeyAlias = StoreUtil.getInstance().getPrivateKeyAlias(); if (clientkeyAlias != null) { final String password = getKeyStoreSystemProperties().get(KEY_STORE_PASSWORD_KEY); if (password != null) { try { pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(clientkeyAlias, new KeyStore.PasswordProtection(password.toCharArray())); } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableEntryException ex) { LOG.error("Error initializing Private Key: {}", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getLocalizedMessage(), ex); } } else { LOG.error("{} is not a defined system property.", KEY_STORE_PASSWORD_KEY); } } else { LOG.error("{} is not a defined system property.", NhincConstants.CLIENT_KEY_ALIAS); } LOG.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End"); return pkEntry; }
Source:
public void testSetInteresting() { GerritEventType type = GerritEventType.CHANGE_MERGED; type.setInteresting(false); assertEquals(false, type.isInteresting()); type.setInteresting(true); assertEquals(true, type.isInteresting()); }

Target:
public void testSetInteresting() { GerritEventType type = GerritEventType.CHANGE_MERGED; try { type.setInteresting(false); assertEquals(false, type.isInteresting()); type.setInteresting(true); assertEquals(true, type.isInteresting()); } finally { type.setInteresting(true); } }
Source:
private Date parseEndTimeJson(JSONObject json) { String endTimeString; try { endTimeString = json.getString(END_TIME); } catch (JSONException e) { return null; } SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); try { Date date = format.parse(endTimeString); return date; } catch (ParseException e) { e.printStackTrace(); } return null; }

Target:
private Date parseEndTimeJson(JSONObject json) { String endTimeString; try { endTimeString = json.getString(END_TIME); } catch (JSONException e) { return null; } SimpleDateFormat format = OneSignalSimpleDateFormat.iso8601Format(); try { Date date = format.parse(endTimeString); return date; } catch (ParseException e) { e.printStackTrace(); } return null; }
Source:
public static final void enforceTetherChangePermission(Context context, String callingPkg) { if (context.getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) { context.enforceCallingOrSelfPermission( android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService"); } else { int uid = Binder.getCallingUid(); if (callingPkg == null) { callingPkg = Settings.getPackageNameForUid(context, uid); } Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg, true ); } }

Target:
public static final void enforceTetherChangePermission(Context context, String callingPkg) { if (null == context || null == callingPkg) { throw new IllegalArgumentException("arguments should not be null"); } if (context.getResources().getStringArray( com.android.internal.R.array.config_mobile_hotspot_provision_app).length == 2) { context.enforceCallingOrSelfPermission( android.Manifest.permission.TETHER_PRIVILEGED, "ConnectivityService"); } else { int uid = Binder.getCallingUid(); Settings.checkAndNoteWriteSettingsOperation(context, uid, callingPkg, true ); } }
Source:
public void onResume() { super.onResume(); addCachedDevices(); if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) removeAllDevices(); if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }

Target:
public void onResume() { super.onResume(); addCachedDevices(); if (mLocalAdapter.getBluetoothState() != BluetoothAdapter.STATE_ON) { removeAllDevices(); } if (mStartScanOnResume) { mLocalAdapter.startScanning(true); mStartScanOnResume = false; } }
Source:
static void validate(Job job, ForecastJobAction.Request request) { if (job.getJobVersion() == null || job.getJobVersion().before(Version.fromString("6.1.0"))) { throw ExceptionsHelper.badRequestException( "Cannot run forecast because jobs created prior to version 6.1 are not supported"); } if (request.getDuration() != null) { TimeValue duration = request.getDuration(); TimeValue bucketSpan = job.getAnalysisConfig().getBucketSpan(); if (duration.compareTo(bucketSpan) < 0) { throw ExceptionsHelper.badRequestException( "[" + DURATION.getPreferredName() + "] must be greater or equal to the bucket span: [" + duration.getStringRep() + "/" + bucketSpan.getStringRep() + "]"); } } if (request.getMaxModelMemory() != null) { if (request.getMaxModelMemory() >= FORECAST_LOCAL_STORAGE_LIMIT.getBytes()) { throw ExceptionsHelper.badRequestException( "[{}] must be less than 500MB", ForecastJobAction.Request.MAX_MODEL_MEMORY.getPreferredName()); } } }

Target:
static void validate(Job job, ForecastJobAction.Request request) { if (job.getJobVersion() == null || job.getJobVersion().before(Version.fromString("6.1.0"))) { throw ExceptionsHelper.badRequestException( "Cannot run forecast because jobs created prior to version 6.1 are not supported"); } if (request.getDuration() != null) { TimeValue duration = request.getDuration(); TimeValue bucketSpan = job.getAnalysisConfig().getBucketSpan(); if (duration.compareTo(bucketSpan) < 0) { throw ExceptionsHelper.badRequestException( "[" + DURATION.getPreferredName() + "] must be greater or equal to the bucket span: [" + duration.getStringRep() + "/" + bucketSpan.getStringRep() + "]"); } } }