auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCertificateChain() throws Exception { KeyStore keystore = CertificateUtil.loadKeyStore("JKS", "changeit", "src/test/resources/cacerts-chain.jks"); Certificate nullObj = null; X509Certificate cert = (X509Certificate) nullObj; Certificate leaf = keystore.getCertificate("gateway"); Certificate interm = keystore.getCertificate("gateway-intermediate"); Certificate root = keystore.getCertificate("gateway-root"); List<Certificate> chain = CertificateUtil.getChain(leaf, keystore); assertEquals(chain.size(), 3); assertTrue("gateway-root is in the chain", CertificateUtil.isInChain(root, chain)); assertTrue("gateway-intermediate is in the chain", CertificateUtil.isInChain(interm, chain)); assertEquals(CertificateUtil.getCertSubjectCN(leaf), "validation.connectopensource.org"); assertNull("Issuer do not have CN", CertificateUtil.getCertSubjectCN(interm)); chain = CertificateUtil.getChain(interm, keystore); assertEquals(chain.size(), 2); keystore = CertificateUtil.loadKeyStore("JKS", "changeit", TRUST_STORE_PATH); leaf = keystore.getCertificate("host1"); chain = CertificateUtil.getChain(leaf, keystore); assertEquals(chain.size(), 1); }

Target:
public void testCertificateChain() throws Exception { KeyStore keystore = CertificateUtil.loadKeyStore("JKS", "changeit", "src/test/resources/cacerts-chain.jks"); Certificate leaf = keystore.getCertificate("gateway"); Certificate interm = keystore.getCertificate("gateway-intermediate"); Certificate root = keystore.getCertificate("gateway-root"); List<Certificate> chain = CertificateUtil.getChain(leaf, keystore); assertEquals(chain.size(), 3); assertTrue("gateway-root is in the chain", CertificateUtil.isInChain(root, chain)); assertTrue("gateway-intermediate is in the chain", CertificateUtil.isInChain(interm, chain)); assertEquals(CertificateUtil.getCertSubjectCN(leaf), "server"); assertEquals(CertificateUtil.getCertSubjectCN(interm), "ca"); assertEquals(CertificateUtil.getCertSubjectCN(root), "root"); chain = CertificateUtil.getChain(interm, keystore); assertEquals(chain.size(), 2); keystore = CertificateUtil.loadKeyStore("JKS", "changeit", TRUST_STORE_PATH); leaf = keystore.getCertificate("host1"); chain = CertificateUtil.getChain(leaf, keystore); assertEquals(chain.size(), 1); }
Source:
public void testSingleCouchbaseEnvironment() throws Exception { ByteArrayOutputStream logs = new ByteArrayOutputStream(); PrintStream logsPrintStream = new PrintStream(logs); PrintStream oldSystemOut = System.out; System.setOut(logsPrintStream); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(new ClassPathResource("configurations/couchbaseSingleEnv-bean.xml")); GenericApplicationContext context = new GenericApplicationContext(factory); context.refresh(); CouchbaseEnvironment env = context.getBean("singleEnv", CouchbaseEnvironment.class); context.close(); System.out.flush(); System.setOut(oldSystemOut); System.out.println(logs.toString()); assertThat(env, is(instanceOf(DefaultCouchbaseEnvironment.class))); assertTrue(logs.toString().indexOf("More than 1 Couchbase Environments found (2)") == -1); }

Target:
public void testSingleCouchbaseEnvironment() throws Exception { Integer instanceCounterBefore = (Integer) ReflectionTestUtils.getField(DefaultCoreEnvironment.class, "instanceCounter"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); BeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(new ClassPathResource("configurations/couchbaseSingleEnv-bean.xml")); GenericApplicationContext context = new GenericApplicationContext(factory); context.refresh(); CouchbaseEnvironment env = context.getBean("singleEnv", CouchbaseEnvironment.class); context.close(); Integer instanceCounterAfter = (Integer) ReflectionTestUtils.getField(DefaultCoreEnvironment.class, "instanceCounter"); assertThat(env, is(instanceOf(DefaultCouchbaseEnvironment.class))); assertThat(instanceCounterAfter, is(instanceCounterBefore + 1)); }
Source:
public String syncBase() { return AnkiDroidApp.getApplicationPrefs().getString("syncBaseUrl", "<LINK_0>"); }

Target:
public String syncBase() { return AnkiDroidApp.getApplicationPrefs().getString("syncBaseUrl", Consts.SYNC_BASE); }
Source:
private IQ handleIq(IQ iq) { IQ responseIq = null; EntityBareJid fromJid = iq.getFrom().asEntityBareJidIfPossible(); String fromJidStr = fromJid.toString().toLowerCase(); if (fromJid == null || !this.config.getMucJids().stream().anyMatch( mucJid -> mucJid.toLowerCase().equals(fromJidStr))) { logger.warn("Received an IQ with unauthorized from:" + fromJid); return IQUtils.createError(iq, XMPPError.Condition.forbidden); } IQListener iqListener = this.iqListener; if (iqListener == null) { logger.error("Received an IQ, but the listener is null."); } else { responseIq = iqListener.handleIq(iq, this); } if (responseIq == null) { logger.info( "Failed to produce a response for IQ, returning internal" + " server error. Request: " +iq.toString()); responseIq = IQUtils.createError( iq, XMPPError.Condition.internal_server_error, "Unknown error"); } return responseIq; }

Target:
private IQ handleIq(IQ iq) { IQ responseIq = null; EntityBareJid fromJid = iq.getFrom().asEntityBareJidIfPossible(); String fromJidStr = fromJid.toString().toLowerCase(); if (fromJid == null || !this.config.getMucJids().stream().anyMatch( mucJid -> mucJid.toLowerCase().equals(fromJidStr))) { logger.warn("Received an IQ from a non-MUC member: " + fromJid); return IQUtils.createError(iq, XMPPError.Condition.forbidden); } IQListener iqListener = this.iqListener; if (iqListener == null) { logger.error("Received an IQ, but the listener is null."); } else { responseIq = iqListener.handleIq(iq, this); } if (responseIq == null) { logger.info( "Failed to produce a response for IQ, returning internal" + " server error. Request: " +iq.toString()); responseIq = IQUtils.createError( iq, XMPPError.Condition.internal_server_error, "Unknown error"); } return responseIq; }
Source:
public Repository createRepository(final Project.NameKey name) throws RepositoryNotFoundException, RepositoryCaseMismatchException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED); FileKey loc; if (dir != null) { loc = FileKey.exact(dir, FS.DETECTED); if (!names.contains(name)) { throw new RepositoryCaseMismatchException(name); } } else { String n = name.get(); n = n + Constants.DOT_GIT_EXT; loc = FileKey.exact(new File(basePath, n), FS.DETECTED); } try { Repository db = RepositoryCache.open(loc, false); db.create(true ); StoredConfig config = db.getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true); config.save(); onCreateProject(name); return db; } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot create repository " + name); e2.initCause(e1); throw e2; } }

Target:
public Repository createRepository(final Project.NameKey name) throws RepositoryNotFoundException, RepositoryCaseMismatchException { if (isUnreasonableName(name)) { throw new RepositoryNotFoundException("Invalid name: " + name); } File dir = FileKey.resolve(gitDirOf(name), FS.DETECTED); FileKey loc; if (dir != null) { loc = FileKey.exact(dir, FS.DETECTED); if (!names.contains(name)) { throw new RepositoryCaseMismatchException(name); } } else { String n = name.get() + Constants.DOT_GIT_EXT; loc = FileKey.exact(new File(basePath, n), FS.DETECTED); } try { Repository db = RepositoryCache.open(loc, false); db.create(true ); StoredConfig config = db.getConfig(); config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_LOGALLREFUPDATES, true); config.save(); onCreateProject(name); return db; } catch (IOException e1) { final RepositoryNotFoundException e2; e2 = new RepositoryNotFoundException("Cannot create repository " + name); e2.initCause(e1); throw e2; } }
Source:
private RaftLeaderElection(Builder builder) { checkNotNull(builder.cluster); this.cluster = builder.cluster; this.heartbeatInterval = builder.heartbeatInterval; this.leadershipTimeout = builder.leadershipTimeout; this.rnd = new Random(); heartbeatTask = new AtomicReference<>(); String nameFormat = "sc-leaderelection-" + cluster.address().toString(); this.executor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build()); subject = PublishSubject.<LeadershipEvent>create().toSerialized(); }

Target:
private RaftLeaderElection(Builder builder) { checkNotNull(builder.cluster); this.cluster = builder.cluster; this.heartbeatInterval = builder.heartbeatInterval; this.electionTimeout = builder.electionTimeout; this.currentTerm = new AtomicInteger(0); this.currentState = new AtomicReference<StateType>(StateType.START); heartbeatTask = new AtomicReference<>(); String nameFormat = "sc-leaderelection-" + cluster.address().toString(); this.executor = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build()); subject = PublishSubject.<LeadershipEvent>create().toSerialized(); }
Source:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_key_notification_pending_drafts))) { if (getActivity() != null) { SharedPreferences prefs = android.support.v7.preference.PreferenceManager.getDefaultSharedPreferences(getActivity()); boolean shouldNotifyOfPendingDrafts = prefs.getBoolean("wp_pref_notification_pending_drafts", true); if (shouldNotifyOfPendingDrafts) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_PENDING_DRAFTS_SETTINGS_ENABLED); } else { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_PENDING_DRAFTS_SETTINGS_DISABLED); } } } else if (key.equals(getString(R.string.wp_pref_custom_notification_sound))) { final String defaultPath = getString(R.string.notification_settings_item_sights_and_sounds_choose_sound_default); final String value = sharedPreferences.getString(key, defaultPath); if (value.trim().startsWith("file://")) { AppLog.w(T.NOTIFS, "Notification sound starts with unacceptable scheme: " + value); Context context = getActivity(); if (context != null && isAdded()) { ToastUtils.showToast(context, R.string.notification_sound_has_invalid_path); } } } }

Target:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_key_notification_pending_drafts))) { if (getActivity() != null) { SharedPreferences prefs = android.support.v7.preference.PreferenceManager.getDefaultSharedPreferences(getActivity()); boolean shouldNotifyOfPendingDrafts = prefs.getBoolean("wp_pref_notification_pending_drafts", true); if (shouldNotifyOfPendingDrafts) { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_PENDING_DRAFTS_SETTINGS_ENABLED); } else { AnalyticsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_PENDING_DRAFTS_SETTINGS_DISABLED); } } } else if (key.equals(getString(R.string.wp_pref_custom_notification_sound))) { final String defaultPath = getString(R.string.notification_settings_item_sights_and_sounds_choose_sound_default); final String value = sharedPreferences.getString(key, defaultPath); if (value.trim().toLowerCase().startsWith("file://")) { AppLog.w(T.NOTIFS, "Notification sound starts with unacceptable scheme: " + value); Context context = WordPress.getContext(); if (context != null) { ToastUtils.showToast(context, R.string.notification_sound_has_invalid_path, Duration.LONG); } } } }
Source:
private void analyzeFile(File inputFile, Optional<CommonTokenStream> optTokenStream, Optional<TopLevelContext> optTree, Formatter formatter, Severity maxSeverity, ConstructLengths constructLengths, Set<Rules> enabledRules) throws CliArgumentParserException { try { Printer printer = new Printer(inputFile, maxSeverity, formatter); if (optTokenStream.isPresent() && optTree.isPresent()) { CommonTokenStream tokenStream = optTokenStream.get(); TopLevelContext tree = optTree.get(); List<SwiftBaseListener> listeners = createListeners( enabledRules, printer, tokenStream, constructLengths ); walkParseTree(listeners, tree); try (FileListener fileListener = new FileListener(printer, inputFile, constructLengths, enabledRules)) { fileListener.verify(); } numErrors.addAndGet(printer.getNumErrorMessages()); numWarnings.addAndGet(printer.getNumWarningMessages()); } else { printer.setShouldPrintParseErrorMessage(true); } printersForAllFiles.add(printer); } catch (IOException e) { handleIoException(e); } catch (CliArgumentParserException e) { handleCliException(e, configuration); } }

Target:
private void analyzeFile(File inputFile, Optional<CommonTokenStream> optTokenStream, Optional<TopLevelContext> optTree, Formatter formatter, Severity maxSeverity, ConstructLengths constructLengths, Set<Rules> enabledRules) throws CLIArgumentParserException { try { Printer printer = new Printer(inputFile, maxSeverity, formatter); if (optTokenStream.isPresent() && optTree.isPresent()) { CommonTokenStream tokenStream = optTokenStream.get(); TopLevelContext tree = optTree.get(); List<SwiftBaseListener> listeners = createListeners(enabledRules, printer, tokenStream, constructLengths); walkParseTree(listeners, tree); try (FileListener fileListener = new FileListener(printer, inputFile, constructLengths, enabledRules)) { fileListener.verify(); } numErrors.addAndGet(printer.getNumErrorMessages()); numWarnings.addAndGet(printer.getNumWarningMessages()); } else { printer.setShouldPrintParseErrorMessage(true); } printersForAllFiles.add(printer); } catch (IOException e) { handleIOException(e); } catch (CLIArgumentParserException e) { handleCLIException(e, configuration); } }
Source:
public void onClick(View view) { final int id = view.getId(); if (id == R.id.button_done) { run(); } else if (id == R.id.trouble_signing_in) { startActivity(RecoverPasswordActivity.createIntent( this, mActivityHelper.getFlowParams(), mEmail)); finish(ResultCodes.CANCELED, IdpResponse.getErrorCodeIntent(ErrorCodes.UNKNOWN_ERROR)); } }

Target:
public void onClick(View view) { final int id = view.getId(); if (id == R.id.button_done) { validateAndSignIn(); } else if (id == R.id.trouble_signing_in) { startActivity(RecoverPasswordActivity.createIntent( this, mActivityHelper.getFlowParams(), mEmail)); finish(ResultCodes.CANCELED, IdpResponse.getErrorCodeIntent(ErrorCodes.UNKNOWN_ERROR)); } }
Source:
Finder obtainFinder(Class<?> type) { Finder finder = findersByType.get(type); if (finder == null) { Class<?> typeFinder = null; Class<?> typeToLoad = type; while (typeFinder == null && typeToLoad != Object.class) { try { typeFinder = Class.forName(PACKAGE_PREFIX + typeToLoad.getSimpleName() + FINDER_SUFFIX); } catch (ClassNotFoundException ignored) { typeToLoad = typeToLoad.getSuperclass(); } } if (typeFinder != null) { try { finder = (Finder) typeFinder.newInstance(); findersByType.put(type, finder); return finder; } catch (InstantiationException e) { throw new RuntimeException("Unable to instantiate generated finder instance.", e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to instantiate generated finder instance.", e); } } } return fallbackFinder; }

Target:
Finder obtainFinder(Class<?> type) { Finder finder = findersByType.get(type); if (finder == null) { Class<?> typeFinder = null; Class<?> typeToLoad = type; while (typeFinder == null && typeToLoad != Object.class) { try { typeFinder = Class.forName(typeToLoad.getName() + FINDER_SUFFIX); } catch (ClassNotFoundException ignored) { typeToLoad = typeToLoad.getSuperclass(); } } if (typeFinder != null) { try { finder = (Finder) typeFinder.newInstance(); findersByType.put(type, finder); } catch (InstantiationException e) { throw new RuntimeException("Unable to instantiate generated finder instance.", e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to instantiate generated finder instance.", e); } } else { finder = fallbackFinder; } } return finder; }
Source:
private byte[] decryptFragment(byte[] ciphertextFragment, final DTLSConnectionState currentReadState) throws GeneralSecurityException { if (currentReadState == null) { return ciphertextFragment; } byte[] result = ciphertextFragment; CipherSuite cipherSuite = currentReadState.getCipherSuite(); LOGGER.trace("Decrypting record fragment using current read state{}{}", StringUtil.lineSeparator(), currentReadState); try { switch (cipherSuite.getCipherType()) { case NULL: break; case AEAD: result = decryptAEAD(ciphertextFragment, currentReadState); break; case BLOCK: result = decryptBlockCipher(ciphertextFragment, currentReadState); break; case STREAM: break; default: break; } } catch(RuntimeException ex) { throw new GeneralSecurityException(ex.getMessage(), ex); } return result; }

Target:
private byte[] decryptFragment(byte[] ciphertextFragment, final DTLSConnectionState currentReadState) throws GeneralSecurityException { if (currentReadState == null) { return ciphertextFragment; } byte[] result = ciphertextFragment; CipherSuite cipherSuite = currentReadState.getCipherSuite(); LOGGER.trace("Decrypting record fragment using current read state{}{}", StringUtil.lineSeparator(), currentReadState); switch (cipherSuite.getCipherType()) { case NULL: break; case AEAD: result = decryptAEAD(ciphertextFragment, currentReadState); break; case BLOCK: result = decryptBlockCipher(ciphertextFragment, currentReadState); break; case STREAM: break; default: break; } return result; }
Source:
public List<TimeDataPoint> uniqueCounts(String metricId, Interval interval, DateTime from, DateTime to) { final List<String> keys = getKeys(metricId, interval, from, to); final List<Boolean> exists = keyExists(keys); List<TimeDataPoint> results = new ArrayList<TimeDataPoint>(keys.size()); for (int i = 0; i < keys.size(); i++) { if (exists.get(i)) { String count = zsetOps.size(keys.get(i)).toString(); long timestamp = PosixTimeUtil.floorToDay(from) * 1000L; results.add(new TimeDataPoint(timestamp, count)); } } return Collections.unmodifiableList(results); }

Target:
public List<TimeDataPoint> uniqueCounts(String metricId, Interval interval, DateTime from, DateTime to) { final List<KeyPiece> keys = getKeys(metricId, interval, from, to); final List<KeyPiece> existingKeys = getExistingKeys(keys); List<Object> counts = redisTemplate.executePipelined(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection conn) throws DataAccessException { StringRedisConnection redisConn = (StringRedisConnection)conn; for (KeyPiece k : existingKeys) { redisConn.zCard(k.key); } return null; } }); if (existingKeys.size() != counts.size()) { throw new RuntimeException("Impedence mismatch between the list of existing keys and the list of counts."); } List<TimeDataPoint> results = new ArrayList<TimeDataPoint>(existingKeys.size()); for (int i = 0; i < existingKeys.size(); i++) { results.add(new TimeDataPoint( existingKeys.get(i).posixTime * 1000L, ((Long)counts.get(i)).toString())); } return Collections.unmodifiableList(results); }
Source:
public static void tearDownSuite() { if (Property.REUSE_BROWSER.isSpecified()) { for (Driver driver : driverPool) { driver.getDriver().quit(); } } }

Target:
public static void tearDownSuite() { if (Property.REUSE_BROWSER.isSpecified()) { driverPool.forEach(d -> d.getDriver().quit()); } }
Source:
public int compare(File f1, File f2) { return (int)(f2.lastModified() - f1.lastModified()); }

Target:
public int compare(File f1, File f2) { return Long.compare(f2.lastModified(), f1.lastModified()); }
Source:
protected boolean isTokenRequest(final WebContext context) { return ContextHelper.isGet(context) && CommonHelper.isNotBlank(context.getRequestParameter(CasConfiguration.TICKET_PARAMETER).orElse(null)); }

Target:
protected boolean isTokenRequest(final WebContext context) { return ContextHelper.isGet(context) && CommonHelper.isNotBlank(context.getRequestParameter(CasConfiguration.TICKET_PARAMETER)); }
Source:
private static List<Double> doubleSequence(double start, double step, int items) { List<Double> values = new ArrayList<>(); double nextValue = start; for (int i = 0; i < items; i++) { values.add(nextValue); nextValue += step; } return values; }

Target:
private static List<Double> doubleSequence(double start, double step, int items) { return IntStream.range(0, items) .mapToDouble(i -> start + i * step) .boxed() .collect(ImmutableList.toImmutableList()); }
Source:
public RunResult invoke( Object forkTestSet ) throws TestSetFailedException, ReporterException { ReporterFactory reporterFactory = parameters.getReporterFactory(); RunListener runListener = reporterFactory.createReporter(); ConsoleOutputCapture.startCapture( (ConsoleOutputReceiver) runListener ); if ( forkTestSet instanceof TestsToRun ) { invokeAllTests( (TestsToRun) forkTestSet, runListener ); } else if ( forkTestSet instanceof Class ) { invokeAllTests( TestsToRun.fromClass( (Class<?>) forkTestSet ), runListener ); } else if ( forkTestSet == null ) { invokeAllTests( scanClasspath(), runListener ); } else { throw new IllegalArgumentException( "Unexpected value of forkTestSet: " + forkTestSet ); } return reporterFactory.close(); }

Target:
public RunResult invoke( Object forkTestSet ) throws TestSetFailedException, ReporterException { ReporterFactory reporterFactory = parameters.getReporterFactory(); final RunResult runResult; try { RunListener runListener = reporterFactory.createReporter(); startCapture( ( ConsoleOutputReceiver ) runListener ); if ( forkTestSet instanceof TestsToRun ) { invokeAllTests( (TestsToRun) forkTestSet, runListener ); } else if ( forkTestSet instanceof Class ) { invokeAllTests( fromClass( ( Class<?> ) forkTestSet ), runListener ); } else if ( forkTestSet == null ) { invokeAllTests( scanClasspath(), runListener ); } else { throw new IllegalArgumentException( "Unexpected value of forkTestSet: " + forkTestSet ); } } finally { runResult = reporterFactory.close(); } return runResult; }
Source:
public void OnUnzipFailure(String cause) { if (!StringUtils.isEmpty(cause)) { txtInteractiveMessages.setText(Localization.get("archive.install.error", new String[]{cause})); transplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem); } }

Target:
public void OnUnzipFailure(String cause) { if (!TextUtils.isEmpty(cause)) { txtInteractiveMessages.setText(Localization.get("archive.install.error", new String[]{cause})); } transplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem); }
Source:
public DocumentValidationException(DocumentValidationReport report) { super(HttpServletResponse.SC_PRECONDITION_FAILED); this.report = report; }

Target:
public DocumentValidationException(DocumentValidationReport report) { super(HttpStatus.SC_UNPROCESSABLE_ENTITY); this.report = report; }
Source:
public @Nullable Integer resolve(ITmfEvent event) { Object cpuObj = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpuObj == null) { return null; } Integer cpu = (Integer) cpuObj; Iterable<KernelAnalysis> kernelModules = TmfTraceUtils .getAnalysisModulesOfClass(event.getTrace(), KernelAnalysis.class); for (KernelAnalysis analysis : kernelModules) { if (analysis == null) { continue; } Integer tid = KernelThreadInformationProvider.getThreadOnCpu( analysis, cpu, event.getTimestamp().getValue()); if (tid != null) { return tid; } } return null; }

Target:
public @Nullable Integer resolve(ITmfEvent event) { Object cpuObj = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), TmfCpuAspect.class, event); if (cpuObj == null) { return null; } Integer cpu = (Integer) cpuObj; KernelAnalysis analysis = TmfTraceUtils.getAnalysisModuleOfClass(event.getTrace(), KernelAnalysis.class, KernelAnalysis.ID); if (analysis == null) { return null; } Integer tid = KernelThreadInformationProvider.getThreadOnCpu( analysis, cpu, event.getTimestamp().getValue()); if (tid != null) { return tid; } return null; }
Source:
protected void unpackCommonFields(Element documentElement) throws InvalidReportException { version = XmlUtil.getTextValue(documentElement, "FitNesseVersion"); rootPath = XmlUtil.getTextValue(documentElement, "rootPath"); String dateString = XmlUtil.getTextValue(documentElement, "date"); if (dateString != null) try { date = DateTimeUtil.getDateFromString(dateString); } catch (ParseException e) { throw new InvalidReportException(String.format("'%s' is not a valid date.", dateString), e); } unpackFinalCounts(documentElement); totalRunTimeInMillis = getTotalRunTimeInMillisOrZeroIfNotPresent(documentElement); }

Target:
protected void unpackCommonFields(Element documentElement) throws InvalidReportException { version = XmlUtil.getTextValue(documentElement, "FitNesseVersion"); rootPath = XmlUtil.getTextValue(documentElement, "rootPath"); String dateString = XmlUtil.getTextValue(documentElement, "date"); if (dateString != null) try { date = DateTimeUtil.getDateFromString(dateString); } catch (ParseException e) { throw new InvalidReportException(format("'%s' is not a valid date.", dateString), e); } unpackFinalCounts(documentElement); totalRunTimeInMillis = getTotalRunTimeInMillisOrZeroIfNotPresent(documentElement); }
Source:
@Autowired ZipkinHttpCollector(StorageComponent storage, CollectorSampler sampler, CollectorMetrics metrics, Optional<List<SpanFilter>> filters) { this.metrics = metrics.forTransport("http"); this.collector = Collector.builder(ZipkinHttpCollector.class) .storage(storage).sampler(sampler).metrics(this.metrics).filters(filters.orElse(Collections.emptyList())).build(); this.JSON_V2 = new HttpCollector(new V2JsonSpanDecoder()); this.PROTO3 = new HttpCollector(new V2Proto3SpanDecoder()); this.JSON_V1 = new HttpCollector(JSON_DECODER); this.THRIFT = new HttpCollector(THRIFT_DECODER); this.errorCallback = new Receiver.ErrorCallback() { @Override public void error(HttpServerExchange exchange, IOException e) { ZipkinHttpCollector.this.metrics.incrementMessagesDropped(); ZipkinHttpCollector.error(exchange, e); } }; }

Target:
ZipkinHttpCollector( StorageComponent storage, CollectorSampler sampler, CollectorMetrics metrics, Optional<List<SpanFilter>> filters) { this.metrics = metrics.forTransport("http"); this.collector = Collector.newBuilder(getClass()) .storage(storage) .sampler(sampler) .metrics(this.metrics) .filters(filters.orElse(Collections.emptyList())) .build(); this.JSON_V2 = new HttpCollector(SpanBytesDecoder.JSON_V2); this.PROTO3 = new HttpCollector(SpanBytesDecoder.PROTO3); this.JSON_V1 = new HttpCollector(SpanBytesDecoder.JSON_V1); this.THRIFT = new HttpCollector(SpanBytesDecoder.THRIFT); this.errorCallback = new Receiver.ErrorCallback() { @Override public void error(HttpServerExchange exchange, IOException e) { ZipkinHttpCollector.this.metrics.incrementMessagesDropped(); ZipkinHttpCollector.error(exchange, e); } }; }
Source:
synchronized void onSyncReply(final String serverId, final String workerId) { if (!ongoingSyncs.containsKey(serverId)) { LOG.log(Level.WARNING, "Sync for {0} is already completed", serverId); return; } LOG.log(Level.INFO, "Sync reply for {0} has been arrived from worker {1}", new Object[]{serverId, workerId}); final Set<String> workersToCheck = ongoingSyncs.get(serverId); workersToCheck.remove(workerId); synchronized (workersToCheck) { workersToCheck.notify(); } }

Target:
synchronized void onSyncReply(final String serverId, final String workerId) { if (!ongoingSyncs.containsKey(serverId)) { LOG.log(Level.WARNING, "Sync for {0} is already completed", serverId); return; } LOG.log(Level.INFO, "Sync reply for {0} has been arrived from worker {1}", new Object[]{serverId, workerId}); final Tuple<Set<String>, EventHandler<Void>> workerSetAndCallback = ongoingSyncs.get(serverId); if (handleWorkerResponseForSync(workerId, workerSetAndCallback)) { ongoingSyncs.remove(serverId); } }
Source:
protected DatabaseImpl(File dir, KeyProvider provider) throws SQLException, IOException, DatastoreException { Misc.checkNotNull(dir, "Directory"); Misc.checkNotNull(provider, "Key provider"); this.keyProvider = provider; this.datastoreDir = dir; this.extensionsDir = new File(dir, "extensions"); final String dbFilename = new File(this.datastoreDir, DB_FILE_NAME).getAbsolutePath(); queue = new SQLDatabaseQueue(dbFilename, provider); int dbVersion = queue.getVersion(); int highestSupportedVersionExclusive = 300; if (dbVersion >= highestSupportedVersionExclusive) { throw new DatastoreException(String.format("Database version is higher than the " + "version supported by this library, current version %d , highest supported " + "version %d", dbVersion, highestSupportedVersionExclusive - 1)); } queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion3()), 3); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion4()), 4); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion5()), 5); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion6()), 6); queue.updateSchema(new MigrateDatabase6To100(), 100); queue.updateSchema(new MigrateDatabase100To200(DatastoreConstants.getSchemaVersion200()), 200); this.eventBus = new EventBus(); this.attachmentsDir = this.extensionDataFolder(ATTACHMENTS_EXTENSION_NAME); this.attachmentStreamFactory = new AttachmentStreamFactory(this.getKeyProvider()); }

Target:
DatabaseImpl(File dir, KeyProvider provider) throws SQLException, IOException, DatastoreException { Misc.checkNotNull(dir, "Directory"); Misc.checkNotNull(provider, "Key provider"); this.keyProvider = provider; this.datastoreDir = dir; this.extensionsDir = new File(dir, "extensions"); final String dbFilename = new File(this.datastoreDir, DB_FILE_NAME).getAbsolutePath(); queue = new SQLDatabaseQueue(dbFilename, provider); int dbVersion = queue.getVersion(); int highestSupportedVersionExclusive = 300; if (dbVersion >= highestSupportedVersionExclusive) { throw new DatastoreException(String.format("Database version is higher than the " + "version supported by this library, current version %d , highest supported " + "version %d", dbVersion, highestSupportedVersionExclusive - 1)); } queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion3()), 3); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion4()), 4); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion5()), 5); queue.updateSchema(new SchemaOnlyMigration(DatastoreConstants.getSchemaVersion6()), 6); queue.updateSchema(new MigrateDatabase6To100(), 100); queue.updateSchema(new MigrateDatabase100To200(DatastoreConstants.getSchemaVersion200()), 200); this.eventBus = new EventBus(); this.attachmentsDir = this.extensionDataFolder(ATTACHMENTS_EXTENSION_NAME); this.attachmentStreamFactory = new AttachmentStreamFactory(this.getKeyProvider()); }
Source:
public void init(ZeppelinConfiguration conf) throws IOException { oneWaySync = conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_ONE_WAY_SYNC); String allStorageClassNames = conf.getNotebookStorageClass().trim(); if (allStorageClassNames.isEmpty()) { allStorageClassNames = DEFAULT_STORAGE; LOGGER.warn("Empty ZEPPELIN_NOTEBOOK_STORAGE conf parameter, using default {}", DEFAULT_STORAGE); } String[] storageClassNames = allStorageClassNames.split(","); if (storageClassNames.length > getMaxRepoNum()) { LOGGER.warn("Unsupported number of storage classes in ZEPPELIN_NOTEBOOK_STORAGE : {}\n" + "first will be used", storageClassNames.length, allStorageClassNames, getMaxRepoNum()); } for (int i = 0; i < Math.min(storageClassNames.length, getMaxRepoNum()); i++) { NotebookRepo notebookRepo = PluginManager.get().loadNotebookRepo(storageClassNames[i].trim()); if (notebookRepo != null) { notebookRepo.init(conf); repos.add(notebookRepo); } } if (getRepoCount() == 0) { LOGGER.info("No storage could be initialized, using default storage", DEFAULT_STORAGE); NotebookRepo defaultNotebookRepo = PluginManager.get().loadNotebookRepo(DEFAULT_STORAGE); defaultNotebookRepo.init(conf); repos.add(defaultNotebookRepo); } if (getRepoCount() > 1 && conf.getBoolean(ConfVars.ZEPPELIN_ANONYMOUS_ALLOWED)) { try { sync(AuthenticationInfo.ANONYMOUS); } catch (IOException e) { LOGGER.error("Couldn't sync on start ", e); } } }

Target:
public void init(ZeppelinConfiguration conf) throws IOException { oneWaySync = conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_ONE_WAY_SYNC); String allStorageClassNames = conf.getNotebookStorageClass().trim(); if (allStorageClassNames.isEmpty()) { allStorageClassNames = DEFAULT_STORAGE; LOGGER.warn("Empty ZEPPELIN_NOTEBOOK_STORAGE conf parameter, using default {}", DEFAULT_STORAGE); } String[] storageClassNames = allStorageClassNames.split(","); if (storageClassNames.length > getMaxRepoNum()) { LOGGER.warn("Unsupported number of storage classes in ZEPPELIN_NOTEBOOK_STORAGE : {}\n" + "first will be used", storageClassNames.length, allStorageClassNames, getMaxRepoNum()); } for (int i = 0; i < Math.min(storageClassNames.length, getMaxRepoNum()); i++) { NotebookRepo notebookRepo = PluginManager.get().loadNotebookRepo(storageClassNames[i].trim()); if (notebookRepo != null) { notebookRepo.init(conf); repos.add(notebookRepo); } } if (getRepoCount() == 0) { LOGGER.info("No storage could be initialized, using default storage", DEFAULT_STORAGE); NotebookRepo defaultNotebookRepo = PluginManager.get().loadNotebookRepo(DEFAULT_STORAGE); defaultNotebookRepo.init(conf); repos.add(defaultNotebookRepo); } if (getRepoCount() > 1 && conf.getBoolean(ConfVars.ZEPPELIN_ANONYMOUS_ALLOWED)) { try { sync(AuthenticationInfo.ANONYMOUS); } catch (IOException e) { LOGGER.error("Couldn't sync anonymous mode on start ", e); } } }
Source:
public @NonNull String getHelpText() { return "Segment duration"; }

Target:
public @NonNull String getHelpText() { return Messages.getString("SegmentDurationAspect.durationDescription"); }
Source:
void registerCommandDispatchers() { CommandClass commandTypeToIntercept = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(context.eventBus(), commandTypeToIntercept); context.withHandlers(dispatcher); context.receivesCommand(registerCommandDispatcher(dispatcher.getClass())); assertThat(dispatcher.commandsIntercepted()).isEqualTo(1); }

Target:
void registerCommandDispatchers() { CommandClass commandTypeToDispatch = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(context.eventBus(), commandTypeToDispatch); context.withHandlers(dispatcher); context.receivesCommand(registerCommandDispatcher(dispatcher.getClass())); assertThat(dispatcher.commandsDispatched()).isEqualTo(1); }
Source:
public void removeByHandle(String handle) { try { logger.info("Removing handle from storage", handle); storageLock.lock(); if (_storage == null) { logger.warn(EXCEPTION_STORAGE); } else { _storage.remove(ACCESS_TOKEN_RESPONSE.getKey(handle)); _storage.remove(LAST_USED.getKey(handle)); _storage.remove(SERVICE_CONFIGURATION.getKey(handle)); } } finally { storageLock.unlock(); } }

Target:
public void removeByHandle(String handle) { logger.debug("Removing handle from storage", handle); storageLock.lock(); try { if (allHandles.remove(handle)) { if (storage == null) { throw new IllegalStateException(EXCEPTION_STORAGE); } storage.remove(ACCESS_TOKEN_RESPONSE.getKey(handle)); storage.remove(LAST_USED.getKey(handle)); storage.remove(SERVICE_CONFIGURATION.getKey(handle)); storage.put(STORE_KEY_INDEX_OF_HANDLES, gson.toJson(allHandles)); } } finally { storageLock.unlock(); } }
Source:
void read(HttpServletRequest request, HttpServletResponse response, AssetFileIdentity id) throws IOException { RepoObjectMetadata objMeta; try { objMeta = contentRepoService.getLatestRepoObjectMetadata(id.toString()); } catch (ContentRepoException e) { if (e.getErrorType() == ErrorType.ErrorFetchingObjectMeta) { throw reportNotFound(id); } else { throw e; } } String contentType = objMeta.getContentType().get(); if (contentType == null) { contentType = id.inferContentType().toString(); } response.setHeader(HttpHeaders.CONTENT_TYPE, contentType); String filename = objMeta.getDownloadName().get(); if (filename == null) { filename = id.getFileName(); } String contentDisposition = "attachment; filename=" + filename; response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); Timestamp timestamp = objMeta.getTimestamp(); setLastModifiedHeader(response, timestamp); if (!checkIfModifiedSince(request, timestamp)) { response.setStatus(HttpStatus.NOT_MODIFIED.value()); return; } List<URL> reproxyUrls = objMeta.getReproxyUrls(); if (clientSupportsReproxy(request) && reproxyUrls != null && !reproxyUrls.isEmpty()) { String reproxyUrlHeader = REPROXY_URL_JOINER.join(reproxyUrls); response.setStatus(HttpStatus.OK.value()); response.setHeader("X-Reproxy-URL", reproxyUrlHeader); response.setHeader("X-Reproxy-Cache-For", REPROXY_CACHE_FOR_HEADER); } else { try (InputStream fileStream = assetCrudService.read(id); OutputStream responseStream = response.getOutputStream()) { ByteStreams.copy(fileStream, responseStream); } } }

Target:
void read(HttpServletRequest request, HttpServletResponse response, AssetFileIdentity id) throws IOException { RepoObjectMetadata objMeta; try { objMeta = contentRepoService.getLatestRepoObjectMetadata(id.toString()); } catch (ContentRepoException e) { if (e.getErrorType() == ErrorType.ErrorFetchingObjectMeta) { throw reportNotFound(id); } else { throw e; } } Optional<String> contentType = objMeta.getContentType(); response.setHeader(HttpHeaders.CONTENT_TYPE, contentType.or(id.inferContentType().toString())); Optional<String> filename = objMeta.getDownloadName(); String contentDisposition = "attachment; filename=" + filename.or(id.getFileName()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); Timestamp timestamp = objMeta.getTimestamp(); setLastModifiedHeader(response, timestamp); if (!checkIfModifiedSince(request, timestamp)) { response.setStatus(HttpStatus.NOT_MODIFIED.value()); return; } List<URL> reproxyUrls = objMeta.getReproxyUrls(); if (clientSupportsReproxy(request) && reproxyUrls != null && !reproxyUrls.isEmpty()) { String reproxyUrlHeader = REPROXY_URL_JOINER.join(reproxyUrls); response.setStatus(HttpStatus.OK.value()); response.setHeader("X-Reproxy-URL", reproxyUrlHeader); response.setHeader("X-Reproxy-Cache-For", REPROXY_CACHE_FOR_HEADER); } else { try (InputStream fileStream = assetCrudService.read(id); OutputStream responseStream = response.getOutputStream()) { ByteStreams.copy(fileStream, responseStream); } } }
Source:
public synchronized void flush() throws IOException { if (closed) { throw new IllegalStateException("Cannot flush when the BufferedMutator is closed."); } try { while(inflightOperations.size() > 0) { LOG.debug("inflight operations: %d currentWriteBufferSize:%d", inflightOperations.size(), currentWriteBufferSize.get()); wait(); } } catch (InterruptedException e) { LOG.error("Encountered exception in flush(). Exception: %s", e); throw new IOException("Flush error", e); } handleExceptions(); }

Target:
public void flush() throws IOException { WriteLock lock = mutationLock.writeLock(); lock.lock(); try { doFlush(); } finally { lock.unlock(); } }
Source:
public XSSFWorkbook createWorkBook() { workBook = new XSSFWorkbook(); XSSFSheet sheet = workBook.createSheet("sheet1"); int rowNumber = 0; if (!Strings.isNullOrEmpty(fileContent)) { String[] lines = fileContent.split(Const.EOL); for (String line : lines) { String[] str = line.split(CSV_LINE_DELIMITTER_REGEX, -1); rowNumber++; XSSFRow currentRow = sheet.createRow(rowNumber); if (line.matches(QUESTION_LINE_REGEX)) { currentRow.setRowStyle(getQuestionStyle()); } else { currentRow.setRowStyle(getDefaultStyle()); } XSSFCell currentCell; for (int i = 0; i < str.length; i++) { currentCell = currentRow.createCell(i); currentCell.setCellStyle(currentRow.getRowStyle()); currentCell.setCellValue(str[i]); } } } return workBook; }

Target:
public XSSFWorkbook createWorkBook() throws IOException { workBook = new XSSFWorkbook(); XSSFSheet sheet = workBook.createSheet("sheet1"); int rowNumber = 0; String[] rows = getIndividualRowsFromContent(fileContent); for (String row : rows) { String[] str = row.split(CSV_LINE_DELIMITTER_REGEX, -1); rowNumber++; XSSFRow currentRow = sheet.createRow(rowNumber); if (row.matches(QUESTION_LINE_REGEX)) { currentRow.setRowStyle(XlsxUtils.getQuestionStyle(workBook)); } else { currentRow.setRowStyle(XlsxUtils.getDefaultStyle(workBook)); } XSSFCell currentCell; for (int i = 0; i < str.length; i++) { currentCell = currentRow.createCell(i); currentCell.setCellStyle(currentRow.getRowStyle()); currentCell.setCellValue(escapeQuotes(str[i])); } } return workBook; }
Source:
private boolean isDatabaseEmpty(Connection connection) throws SQLException { DatabaseMetaData databaseMetaData = connection.getMetaData(); try (ResultSet resultSet = databaseMetaData.getTables(connection.getCatalog(), connection.getSchema(), "", null)) { if (resultSet.next()) return false; return true; } catch (SQLException e) { throw new SchemaMigrationException("Unable the obtain the state of the target database", e); } }

Target:
private boolean isDatabaseEmpty(Connection connection) throws SQLException { DatabaseMetaData databaseMetaData = connection.getMetaData(); try (ResultSet resultSet = databaseMetaData.getTables(connection.getCatalog(), connection.getSchema(), "", null)) { return !resultSet.next(); } catch (SQLException e) { throw new SchemaMigrationException("Unable the obtain the state of the target database", e); } }
Source:
public void setup(Context.OperatorContext context) { if (store == null) { store = new ManagedStateSpillableStateStore(); } if (bucket == 0) { bucket = (context.getValue(Context.DAGContext.APPLICATION_NAME) + "#" + context.getId()).hashCode(); } if (windowSerde == null) { windowSerde = new SerdeKryoSlice<>(); } if (valueSerde == null) { valueSerde = new SerdeKryoSlice<>(); } sccImpl = new SpillableComplexComponentImpl(store); sccImpl.setup(context); internMap = sccImpl.newSpillableByteMap(bucket, windowSerde, valueSerde); }

Target:
public void setup(Context.OperatorContext context) { if (bucket == 0) { bucket = (context.getValue(Context.DAGContext.APPLICATION_NAME) + "#" + context.getId()).hashCode(); } if (windowSerde == null) { windowSerde = new SerdeKryoSlice<>(); } if (valueSerde == null) { valueSerde = new SerdeKryoSlice<>(); } if (windowToDataMap == null) { windowToDataMap = scc.newSpillableByteMap(bucket, windowSerde, valueSerde); } }
Source:
public AbstractSegmentStoreDensityViewer(Composite parent) { super(parent); fListeners = new ArrayList<>(); fChart = new Chart(parent, SWT.NONE); fChart.getLegend().setVisible(false); fChart.getTitle().setVisible(false); fChart.getAxisSet().getXAxis(0).getTitle().setText(nullToEmptyString(Messages.AbstractSegmentStoreDensityViewer_TimeAxisLabel)); fChart.getAxisSet().getYAxis(0).getTitle().setText(nullToEmptyString(Messages.AbstractSegmentStoreDensityViewer_CountAxisLabel)); fChart.getAxisSet().getXAxis(0).getGrid().setStyle(LineStyle.DOT); fChart.getAxisSet().getYAxis(0).getGrid().setStyle(LineStyle.DOT); fDragZoomProvider = new MouseDragZoomProvider(this); fDragZoomProvider.register(); fDragProvider = new MouseSelectionProvider(this); fDragProvider.register(); fTooltipProvider = new SimpleTooltipProvider(this); fTooltipProvider.register(); fChart.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(@Nullable DisposeEvent e) { internalDispose(); } }); }

Target:
public AbstractSegmentStoreDensityViewer(Composite parent) { super(parent); fListeners = new ArrayList<>(); fChart = new Chart(parent, SWT.NONE); fChart.getLegend().setVisible(false); fChart.getTitle().setVisible(false); fChart.getAxisSet().getXAxis(0).getTitle().setText(nullToEmptyString(Messages.AbstractSegmentStoreDensityViewer_TimeAxisLabel)); fChart.getAxisSet().getYAxis(0).getTitle().setText(nullToEmptyString(Messages.AbstractSegmentStoreDensityViewer_CountAxisLabel)); fChart.getAxisSet().getXAxis(0).getGrid().setStyle(LineStyle.DOT); fChart.getAxisSet().getYAxis(0).getGrid().setStyle(LineStyle.DOT); fDragZoomProvider = new MouseDragZoomProvider(this); fDragZoomProvider.register(); fDragProvider = new MouseSelectionProvider(this); fDragProvider.register(); fTooltipProvider = new SimpleTooltipProvider(this); fTooltipProvider.register(); fChart.addDisposeListener((e) -> { internalDispose(); }); }
Source:
public RecordWriter getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { Configuration conf = taskAttemptContext.getConfiguration(); try { return new FileCopyRecordWriter(conf); } catch (Exception e) { throw new IOException(e.getMessage()); } }

Target:
public RecordWriter getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { Configuration conf = taskAttemptContext.getConfiguration(); return new FileCopyRecordWriter(conf); }
Source:
public static boolean hasOverlap(ReaderPostList posts, ReaderTag tag) { for (ReaderPost post : posts) { if (ReaderPostTable.postExistsForReaderTag(post.blogId, post.postId, tag)) { return true; } } return false; }

Target:
public static boolean hasOverlap(ReaderPostList posts, ReaderTag tag) { for (ReaderPost post : posts) { if (postExistsForReaderTag(post.blogId, post.postId, tag)) { return true; } } return false; }
Source:
public static String submitPlan(HttpClient client, URI baseUri, String plan) { URI uri = URI.create(Urls.mergePaths(baseUri.toString(), "/v1/applications")); HttpToolResponse result = null; byte[] content; try { result = HttpTool.httpPost(client, uri, MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/yaml"), plan.getBytes()); content = result.getContent(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Invalid response invoking "+uri+": "+e, e); } Tasks.addTagDynamically(BrooklynTaskTags.tagForStream("http_response", Streams.byteArray(content))); if (!isStatusCodeHealthy(result.getResponseCode())) { log.warn("Invalid response invoking "+uri+": response code "+result.getResponseCode()+"\n"+result+": "+new String(content)); throw new IllegalStateException("Invalid response invoking "+uri+": response code "+result.getResponseCode() ); } return (String)new Gson().fromJson(new String(content), Map.class).get("entityId"); }

Target:
public static String submitPlan(HttpClient client, URI baseUri, String plan) { URI uri = URI.create(Urls.mergePaths(baseUri.toString(), "/v1/applications")); HttpToolResponse result = null; byte[] content; try { result = HttpTool.httpPost(client, uri, MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/yaml"), plan.getBytes()); content = result.getContent(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Invalid response invoking "+uri+": "+e, e); } Tasks.addTagDynamically(BrooklynTaskTags.tagForStream("http_response", Streams.byteArray(content))); if (!HttpTool.isStatusCodeHealthy(result.getResponseCode())) { log.warn("Invalid response invoking "+uri+": response code "+result.getResponseCode()+"\n"+result+": "+new String(content)); throw new IllegalStateException("Invalid response invoking "+uri+": response code "+result.getResponseCode()); } return (String)new Gson().fromJson(new String(content), Map.class).get("entityId"); }
Source:
public static void createTable(SQLiteDatabase db) { if (db != null) { db.execSQL(SiteSettingsModel.CREATE_SETTINGS_TABLE_SQL); db.execSQL(JetpackSettingsModel.CREATE_JP_SETTINGS_TABLE_SQL); db.execSQL(CREATE_CATEGORIES_TABLE_SQL); } }

Target:
public static void createTable(SQLiteDatabase db) { if (db != null) { db.execSQL(SiteSettingsModel.CREATE_SETTINGS_TABLE_SQL); db.execSQL(CREATE_JP_SETTINGS_TABLE_SQL); db.execSQL(CREATE_CATEGORIES_TABLE_SQL); } }
Source:
public AbstractRepeatingRunnable(long initialDelay, long period, @NonNull TimeUnit unit, boolean startImmediately) { if(!startImmediately) { throw new UnsupportedOperationException("RepeatingRunnables are immediatly excecuted!"); } ScheduledExecutorService threadExcecutor = Executors.newScheduledThreadPool(0); handle = threadExcecutor.scheduleAtFixedRate(this, initialDelay, period, unit); }

Target:
public AbstractRepeatingRunnable(long initialDelay, long period, @NonNull TimeUnit unit, boolean startImmediately) { if(!startImmediately) { throw new UnsupportedOperationException("RepeatingRunnables are immediately executed!"); } ScheduledExecutorService threadExcecutor = Executors.newScheduledThreadPool(0); handle = threadExcecutor.scheduleAtFixedRate(this, initialDelay, period, unit); }