auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
AzureClient(String storageConnectionString) { try { account = CloudStorageAccount.parse(storageConnectionString); blobClient = account.createCloudBlobClient(); tableClient = account.createCloudTableClient(); } catch (IllegalArgumentException | URISyntaxException e) { LOG.error("\nConnection string specifies an invalid URI.", storageConnectionString); LOG.error("Please confirm the connection string is in the Azure connection string format."); throw new AzureException(e); } catch (InvalidKeyException e) { LOG.error("\nConnection string specifies an invalid key.", storageConnectionString); LOG.error("Please confirm the AccountName and AccountKey in the connection string are valid."); throw new AzureException(e); } }

Target:
AzureClient(String storageConnectionString) { try { account = CloudStorageAccount.parse(storageConnectionString); blobClient = account.createCloudBlobClient(); tableClient = account.createCloudTableClient(); } catch (IllegalArgumentException | URISyntaxException e) { LOG.error("Connection string specifies an invalid URI.", storageConnectionString); LOG.error("Please confirm the connection string is in the Azure connection string format."); throw new AzureException(e); } catch (InvalidKeyException e) { LOG.error("Connection string specifies an invalid key.", storageConnectionString); LOG.error("Please confirm the AccountName and AccountKey in the connection string are valid."); throw new AzureException(e); } }
Source:
public List<T> load() throws IOException { InputStream input = null; RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectTimeout) .setSocketTimeout(readTimeout).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig); if (! useCompression) { LOG.info("Not using compression!"); httpClientBuilder.disableContentCompression(); } else { LOG.info("Using compression by default! Trying gzip, deflate"); } CloseableHttpClient httpClient = httpClientBuilder.build(); HttpGet httpGet = new HttpGet(endpointURL); HttpResponse response = httpClient.execute(httpGet); try { input = response.getEntity().getContent(); return (List<T>) JSONUtil.readJson(input, typeRef); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(httpClient); } }

Target:
public List<T> load() throws IOException { InputStream input = null; RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectTimeout) .setSocketTimeout(readTimeout).build(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig); if (! useCompression) { LOG.info("Not using compression!"); httpClientBuilder.disableContentCompression(); } else { LOG.debug("Using compression by default! Trying gzip, deflate"); } CloseableHttpClient httpClient = httpClientBuilder.build(); HttpGet httpGet = new HttpGet(endpointURL); HttpResponse response = httpClient.execute(httpGet); try { input = response.getEntity().getContent(); return (List<T>) JSONUtil.readJson(input, typeRef); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(httpClient); } }
Source:
public static int floor(double x) { int ix = (int) x; return x < ix ? ix - 1 : ix; }

Target:
public static int floor(double x) { int floored = (int) x; return x < floored ? floored - 1 : floored; }
Source:
public NoAuthPrincipalInjectedResourceConfig() { super(); register(NoAuthPrincipalEntityResource.class); packages("io.dropwizard.jersey.jackson"); }

Target:
public NoAuthPrincipalInjectedResourceConfig() { register(NoAuthPrincipalEntityResource.class); packages("io.dropwizard.jersey.jackson"); }
Source:
public void setupGroovyHome() { groovyVersion = GroovySystem.getVersion(); Configuration groovyConfig = rootProject.getConfigurations().maybeCreate(GROOVY_DEPS_CONFIG); rootProject .getDependencies() .add(GROOVY_DEPS_CONFIG, "org.codehaus.groovy:groovy:" + groovyVersion); dependencies = new DependencyCache(rootProject, ProjectUtil.getDependencyManager(rootProject)) .build(groovyConfig); }

Target:
public void setupGroovyHome() { Configuration groovyConfig = rootProject.getConfigurations().maybeCreate(GROOVY_DEPS_CONFIG); rootProject .getDependencies() .add(GROOVY_DEPS_CONFIG, "org.codehaus.groovy:groovy:" + groovyVersion); dependencies = new DependencyCache(rootProject, ProjectUtil.getDependencyManager(rootProject)) .build(groovyConfig); }
Source:
public Future<T> onComplete(Handler<AsyncResult<T>> h) { if (h == null) { throw new NullPointerException("No null handler accepted"); } synchronized (this) { if (!isComplete()) { if (handler == null) { handler = h; } else { addHandler(h); } return this; } } dispatch(h); return this; }

Target:
public Future<T> onComplete(Handler<AsyncResult<T>> h) { Objects.requireNonNull(h, "No null handler accepted"); synchronized (this) { if (!isComplete()) { if (handler == null) { handler = h; } else { addHandler(h); } return this; } } dispatch(h); return this; }
Source:
public void testAlone() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(RightCurlyCheck.class); checkConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); final String[] expected = { "93:27: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 27), "97:72: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 72), }; verify(checkConfig, getPath("InputRightCurlyLeft.java"), expected); }

Target:
public void testAlone() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(RightCurlyCheck.class); checkConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); checkConfig.addAttribute("tokens", "LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, " + "LITERAL_IF, LITERAL_ELSE, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO"); final String[] expected = { "56:13: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 13), "93:27: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 27), "97:72: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 72), "173:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "175:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "177:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "178:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "183:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "188:9: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 9), "189:53: " + getCheckMessage(MSG_KEY_LINE_ALONE, "}", 53), }; verify(checkConfig, getPath("InputRightCurlyLeft.java"), expected); }
Source:
public Iterator<Node> treeIterator(TreeTraversal traversal) { switch (traversal) { case BREADTHFIRST: return new TreeVisitor.BreadthFirstIterator(this); case POSTORDER: return new TreeVisitor.PostOrderIterator(this); case PREORDER: return new TreeVisitor.PreOrderIterator(this); default: throw new IllegalArgumentException("Unknown traversal choice."); } }

Target:
private Iterator<Node> treeIterator(TreeTraversal traversal) { switch (traversal) { case BREADTHFIRST: return new BreadthFirstIterator(this); case POSTORDER: return new PostOrderIterator(this); case PREORDER: return new PreOrderIterator(this); case DIRECT_CHILDREN: return new DirectChildrenIterator(this); case PARENTS: return new ParentsVisitor(this); default: throw new IllegalArgumentException("Unknown traversal choice."); } }
Source:
public void clientDisconnected(ClientDescriptor clientDescriptor) { connectedClients.remove(clientDescriptor); if (managementRegistry != null) { LOGGER.trace("clientDisconnected({})", clientDescriptor); ClusterTierClientStateBinding clientStateBinding = new ClusterTierClientStateBinding(clientDescriptor); managementRegistry.pushServerEntityNotification(clientStateBinding, EHCACHE_SERVER_STORE_RELEASED.name()); managementRegistry.unregisterAndRefresh(clientStateBinding); } }

Target:
public void clientDisconnected(ClientDescriptor clientDescriptor) { if (managementRegistry != null) { LOGGER.trace("clientDisconnected({})", clientDescriptor); ClusterTierClientDescriptorBinding clientStateBinding = new ClusterTierClientDescriptorBinding(clientDescriptor); managementRegistry.pushServerEntityNotification(clientStateBinding, EHCACHE_SERVER_STORE_RELEASED.name()); managementRegistry.unregisterAndRefresh(clientStateBinding); } }
Source:
ServicePool<S> buildInternal() { checkNotNull(_serviceFactory); HostDiscovery hostDiscovery = findHostDiscovery(_serviceName); try { if (_cachingPolicy == null) { _cachingPolicy = ServiceCachingPolicyBuilder.NO_CACHING; } boolean shutdownHealthCheckExecutorOnClose = (_healthCheckExecutor == null); if (_healthCheckExecutor == null) { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(_serviceName + "-HealthCheckThread-%d") .setDaemon(true) .build(); _healthCheckExecutor = Executors.newScheduledThreadPool(DEFAULT_NUM_HEALTH_CHECK_THREADS, threadFactory); } ServicePool<S> servicePool = new ServicePool<S>(Ticker.systemTicker(), hostDiscovery, _closeHostDiscovery, _serviceFactory, _cachingPolicy, _partitionFilter, _loadBalanceAlgorithm, _healthCheckExecutor, shutdownHealthCheckExecutorOnClose); _closeHostDiscovery = false; return servicePool; } catch (Throwable t) { try { if (_closeHostDiscovery) { hostDiscovery.close(); } } catch (IOException e) { } finally { _closeHostDiscovery = false; } throw Throwables.propagate(t); } }

Target:
ServicePool<S> buildInternal() { checkNotNull(_serviceFactory); HostDiscovery hostDiscovery = findHostDiscovery(_serviceName); boolean shutdownHealthCheckExecutorOnClose = (_healthCheckExecutor == null); try { if (_cachingPolicy == null) { _cachingPolicy = ServiceCachingPolicyBuilder.NO_CACHING; } if (_healthCheckExecutor == null) { ThreadFactory threadFactory = new ThreadFactoryBuilder() .setNameFormat(_serviceName + "-HealthCheckThread-%d") .setDaemon(true) .build(); _healthCheckExecutor = Executors.newScheduledThreadPool(DEFAULT_NUM_HEALTH_CHECK_THREADS, threadFactory); } ServicePool<S> servicePool = new ServicePool<S>(Ticker.systemTicker(), hostDiscovery, _closeHostDiscovery, _serviceFactory, _cachingPolicy, _partitionFilter, _loadBalanceAlgorithm, _healthCheckExecutor, shutdownHealthCheckExecutorOnClose); _closeHostDiscovery = false; return servicePool; } catch (Throwable t) { if (shutdownHealthCheckExecutorOnClose) { _healthCheckExecutor.shutdownNow(); _healthCheckExecutor = null; } try { if (_closeHostDiscovery) { hostDiscovery.close(); } } catch (IOException e) { } finally { _closeHostDiscovery = false; } throw Throwables.propagate(t); } }
Source:
public Citation mapRow(ResultSet rs, int i) { Citation citation = new Citation(); try { citation.id = rs.getInt("id"); citation.citation_number = rs.getString("citation_number"); citation.citation_date = (rs.getDate("citation_date")!=null)?rs.getDate("citation_date").toLocalDate():null; citation.first_name = rs.getString("first_name"); citation.last_name = rs.getString("last_name"); citation.date_of_birth = (rs.getDate("date_of_birth")!=null)?rs.getDate("date_of_birth").toLocalDate():null; citation.defendant_address = rs.getString("defendant_address"); citation.defendant_city = rs.getString("defendant_city"); citation.defendant_state = rs.getString("defendant_state"); citation.drivers_license_number = rs.getString("drivers_license_number"); LocalDate courtDate = (rs.getDate("court_date")!=null)?rs.getDate("court_date").toLocalDate():null; LocalTime courtTime = (rs.getTime("court_date")!=null)?rs.getTime("court_date").toLocalTime():null; if (courtDate==null || courtTime==null){ citation.court_dateTime = null; }else{ citation.court_dateTime = LocalDateTime.of(courtDate, courtTime); } citation.court_location = rs.getString("court_location"); citation.court_address = rs.getString("court_address"); citation.court_id = rs.getLong("court_id"); } catch (Exception e) { LogSystem.LogDBException(e); return null; } return citation; }

Target:
public Citation mapRow(ResultSet rs, int i) { Citation citation = new Citation(); try { citation.id = rs.getInt("id"); citation.citation_number = rs.getString("citation_number"); citation.citation_date = DatabaseUtilities.getDatabaseLocalDate(rs.getDate("citation_date")); citation.first_name = rs.getString("first_name"); citation.last_name = rs.getString("last_name"); citation.date_of_birth = DatabaseUtilities.getDatabaseLocalDate(rs.getDate("date_of_birth")); citation.defendant_address = rs.getString("defendant_address"); citation.defendant_city = rs.getString("defendant_city"); citation.defendant_state = rs.getString("defendant_state"); citation.drivers_license_number = rs.getString("drivers_license_number"); LocalDate courtDate = DatabaseUtilities.getDatabaseLocalDate(rs.getDate("court_date")); LocalTime courtTime = DatabaseUtilities.getDatabaseLocalTime(rs.getTime("court_date")); if (courtDate==null || courtTime==null){ citation.court_dateTime = null; }else{ citation.court_dateTime = LocalDateTime.of(courtDate, courtTime); } citation.court_location = rs.getString("court_location"); citation.court_address = rs.getString("court_address"); citation.court_id = new HashableEntity<Court>(Court.class,rs.getLong("court_id")); } catch (Exception e) { LogSystem.LogDBException(e); return null; } return citation; }
Source:
public void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { trimMark = msg.getPayload(); cache.invalidateUpTo(trimMark); } for(StreamAddressSpace streamAddressSpace : streamsAddressSpaceMap.values()) { streamAddressSpace.trim(trimMark); } r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }

Target:
public void trimCache(CorfuPayloadMsg<Long> msg, ChannelHandlerContext ctx, IServerRouter r) { log.info("trimCache: Starting cache eviction"); if (trimMark < msg.getPayload()) { trimMark = msg.getPayload(); cache.invalidateUpTo(trimMark); } for(StreamAddressSpace streamAddressSpace : streamsAddressMap.values()) { streamAddressSpace.trim(trimMark); } r.sendResponse(ctx, msg, CorfuMsgType.ACK.msg()); }
Source:
public static void register(ScalarFunctionModule module) { module.register(NAME, new FunctionResolver() { @Override public List<DataType> getSignature(List<? extends FuncArg> funcArgs) { return SIGNATURE.match(funcArgs); } @Override public FunctionImplementation getForTypes(List<DataType> types) throws IllegalArgumentException { int argsLen = types.size(); assert argsLen > 0 && argsLen <= 2 : "number of args must be up to 2"; DataType argType = types.get(0); DataType returnType = DataTypes.getIntegralReturnType(argType); return 1 == argsLen ? new OneParamTrunc(argType, returnType) : new TwoParamTrunc(argType, returnType); } }); }

Target:
public static void register(ScalarFunctionModule module) { module.register(NAME, new BaseFunctionResolver(SIGNATURE) { @Override public FunctionImplementation getForTypes(List<DataType> types) throws IllegalArgumentException { DataType argType = types.get(0); DataType returnType = DataTypes.getIntegralReturnType(argType); if (1 == types.size()) { return new UnaryScalar<Number, Number>(NAME, argType, returnType, n -> { double val = n.doubleValue(); Function<Double, Double> f = val >= 0 ? Math::floor : Math::ceil; return (Number) returnType.value(f.apply(val)); }); } else { return new Scalar<Number, Number>() { FunctionInfo info = new FunctionInfo(new FunctionIdent( NAME, types), DataTypes.DOUBLE); @Override public FunctionInfo info() { return info; } @Override public Number evaluate(TransactionContext txnCtx, Input<Number>... args) { Number n = args[0].value(); Number nd = args[1].value(); if (null == n || null == nd) { return null; } double val = n.doubleValue(); int numDecimals = nd.intValue(); RoundingMode mode = val >= 0 ? RoundingMode.FLOOR : RoundingMode.CEILING; return BigDecimal.valueOf(val).setScale(numDecimals, mode).doubleValue(); } }; } } }); }
Source:
public byte[] reEncryptKey(final byte[] externallyEncryptedKey, final SecurityKeyType keyType) throws FunctionalException { if (externallyEncryptedKey == null) { return new byte[0]; } try { final byte[] key = this.rsaEncryptionService.decrypt(externallyEncryptedKey); return this.encryptionService.encrypt(key); } catch (final Exception e) { LOGGER.error("Unexpected exception during encryption", e); throw new FunctionalException(FunctionalExceptionType.ENCRYPTION_EXCEPTION, ComponentType.PROTOCOL_DLMS, new EncrypterException(String.format("Error encryption process with %s key.", keyType))); } }

Target:
public byte[] reEncryptKey(final byte[] externallyEncryptedKey, final SecurityKeyType keyType) throws FunctionalException { if (externallyEncryptedKey == null) { return new byte[0]; } final byte[] key = this.rsaDecrypt(externallyEncryptedKey, keyType); return this.aesEncrypt(key, keyType); }
Source:
public int getId() { try { return id; } catch (RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (Error e) { throw logAndPrepareForRethrow(e); } catch (Throwable t) { throw logAndPrepareForRethrow(t); } }

Target:
public int getId() { return id; }
Source:
public EnergyArc(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{W}{U}"); this.getSpellAbility().addTarget(new TargetCreaturePermanent(0, Integer.MAX_VALUE)); this.getSpellAbility().addEffect(new UntapTargetEffect()); this.getSpellAbility().addEffect(new PreventDamageByTargetEffect(Duration.EndOfTurn, true)); this.getSpellAbility().addEffect(new PreventDamageToTargetEffect(Duration.EndOfTurn, Integer.MAX_VALUE, true)); }

Target:
public EnergyArc(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{W}{U}"); this.getSpellAbility().addTarget(new TargetCreaturePermanent(0, Integer.MAX_VALUE)); this.getSpellAbility().addEffect(new UntapTargetEffect().setText("Untap any number of target creatures. ")); this.getSpellAbility().addEffect(new PreventDamageByTargetEffect(Duration.EndOfTurn, true).setText("Prevent all combat damage that would be dealt to ")); this.getSpellAbility().addEffect(new PreventDamageToTargetEffect(Duration.EndOfTurn, true).setText("and dealt by those creatures this turn.")); }
Source:
private static void addResponseHeaderWithOverride( HttpServletRequest request, HttpServletResponse response, String headerName, String overrideHeaderName, String value) { String override = request.getParameter(overrideHeaderName); if (override != null) { response.addHeader(headerName, override); } else { response.addHeader(headerName, value); } }

Target:
private static void addResponseHeaderWithOverride( HttpServletRequest request, HttpServletResponse response, String headerName, String overrideHeaderName, String value) { String override = request.getParameter(overrideHeaderName); response.addHeader(headerName, override != null ? override : value); }
Source:
public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); View errorView = findViewById(R.id.error_view); if (errorView != null) { errorView.setVisibility(valid ? GONE : VISIBLE); } }

Target:
public void onPostValidation(boolean valid) { FormViewUtil.setupBackground(getContext(), valid, textEditText); FormViewUtil.setupErrorView(valid, findViewById(R.id.error_view)); }
Source:
protected DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { this.protocolLayer = new AzureDigitalTwinsAPIBuilder().host(host).pipeline(pipeline).buildClient(); this.serviceVersion = serviceVersion; }

Target:
DigitalTwinsAsyncClient(HttpPipeline pipeline, DigitalTwinsServiceVersion serviceVersion, String host) { this.protocolLayer = new AzureDigitalTwinsAPIBuilder().host(host).pipeline(pipeline).buildClient(); this.serviceVersion = serviceVersion; }
Source:
public String toString() { return "Alert [triggerId=" + getTriggerId() + ", severity=" + severity + ", status=" + status + ", tenantId=" + tenantId + ", ctime=" + ctime + "]"; }

Target:
public String toString() { return "Alert [tenantId=" + tenantId + ", triggerId=" + getTriggerId() + ", severity=" + severity + ", status=" + status + ", ctime=" + ctime + ", lifecycle=" + lifecycle + ", resolvedEvalSets=" + resolvedEvalSets + "]"; }
Source:
public void endDocument() { while (!blockStrategyState.isEmpty()) { endBlock(); } delegate.endDocument(); }

Target:
public void endDocument() { assertCloseImplicitBlock(); delegate.endDocument(); }
Source:
public void testRemoveContentFromIndexMultilingualContent() throws DotDataException, DotSecurityException, InterruptedException { ContentType contentType = null; try { contentType = new ContentTypeDataGen() .name("testRemoveContentFromIndexMultilingualContent"+System.currentTimeMillis()) .fields(ImmutableList .of(ImmutableTextField.builder().name("Title").variable("title") .build())) .nextPersisted(); final ContentletDataGen contentletDataGen = new ContentletDataGen(contentType.id()); final Contentlet contentInEnglish = contentletDataGen.languageId(languageAPI.getDefaultLanguage().getId()).nextPersisted(); Contentlet contentInSpanish = contentletDataGen.checkout(contentInEnglish); contentInSpanish.setLanguageId(spanishLanguage.getId()); contentInSpanish.setIndexPolicy(IndexPolicy.FORCE); contentInSpanish = contentletDataGen.checkin(contentInSpanish); assertEquals(2, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); contentletDataGen.archive(contentInSpanish); contentletDataGen.delete(contentInSpanish); Thread.sleep(1000); assertEquals(1, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); contentletDataGen.archive(contentInEnglish); contentletDataGen.delete(contentInEnglish); Thread.sleep(1000); assertEquals(0, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); } finally { if (contentType != null) { contentTypeAPI.delete(contentType); } } }

Target:
public void testRemoveContentFromIndexMultilingualContent() throws DotDataException, DotSecurityException, InterruptedException { ContentType contentType = null; try { contentType = new ContentTypeDataGen() .name("testRemoveContentFromIndexMultilingualContent"+System.currentTimeMillis()) .fields(ImmutableList .of(ImmutableTextField.builder().name("Title").variable("title") .build())) .nextPersisted(); final ContentletDataGen contentletDataGen = new ContentletDataGen(contentType.id()); final Contentlet contentInEnglish = contentletDataGen.languageId(languageAPI.getDefaultLanguage().getId()).nextPersisted(); Contentlet contentInSpanish = contentletDataGen.checkout(contentInEnglish); contentInSpanish.setLanguageId(spanishLanguage.getId()); contentInSpanish.setIndexPolicy(IndexPolicy.WAIT_FOR); contentInSpanish = contentletDataGen.checkin(contentInSpanish); assertEquals(2, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); contentletDataGen.archive(contentInSpanish); contentletDataGen.delete(contentInSpanish); assertEquals(1, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); contentletDataGen.archive(contentInEnglish); contentletDataGen.delete(contentInEnglish); assertEquals(0, contentletAPI.searchIndex("+identifier:"+contentInEnglish.getIdentifier(),-1,0,"",user,true).size()); } finally { if (contentType != null) { contentTypeAPI.delete(contentType); } } }
Source:
private Optional<String> getGroupIdToCreate(String documentationOptions) { try { Properties docProps = new Properties(); docProps.load(new StringReader(documentationOptions)); String groupId = docProps.getProperty(GROUP_PREFIX); if (groupId != null) { return Optional.of(groupId); } } catch (IOException e) { } return Optional.empty(); }

Target:
private Optional<String> getGroupIdToCreate(String documentationOptions) { try { Properties docProps = new Properties(); StringReader docReader = new StringReader(documentationOptions); try { docProps.load(docReader); } finally { docReader.close(); } String groupId = docProps.getProperty(GROUP_PREFIX); if (groupId != null) { return Optional.of(groupId); } } catch (IOException e) { } return Optional.empty(); }
Source:
protected void extractAdditionalItemFields(NitroItemSource<Episode> source, Item item, DateTime now) { Episode episode = source.getProgramme(); if (item.getTitle() == null) { item.setTitle(episode.getPresentationTitle()); } if (isHasMoreThanOneSeriesAncestor(episode)) { item.setTitle(compileTitleForSeriesSeriesEpisode(episode)); } if (episode.getEpisodeOf() != null) { org.atlasapi.media.entity.Episode episodeContent = (org.atlasapi.media.entity.Episode) item; BigInteger position = episode.getEpisodeOf().getPosition(); if (position != null) { episodeContent.setEpisodeNumber(position.intValue()); } episodeContent.setSeriesRef(getSeriesRef(episode)); } item.setParentRef(getBrandRef(episode)); item.setGenres(genresExtractor.extract(source.getGenres())); }

Target:
protected void extractAdditionalItemFields(NitroItemSource<Episode> source, Item item, DateTime now) { Episode episode = source.getProgramme(); if (item.getTitle() == null) { item.setTitle(episode.getPresentationTitle()); } if (hasMoreThanOneSeriesAncestor(episode)) { item.setTitle(compileTitleForSeriesSeriesEpisode(episode)); } if (episode.getEpisodeOf() != null) { org.atlasapi.media.entity.Episode episodeContent = (org.atlasapi.media.entity.Episode) item; BigInteger position = episode.getEpisodeOf().getPosition(); if (position != null) { episodeContent.setEpisodeNumber(position.intValue()); } episodeContent.setSeriesRef(getSeriesRef(episode)); } item.setParentRef(getBrandRef(episode)); item.setGenres(genresExtractor.extract(source.getGenres())); }
Source:
public void clearCache() { DotCacheAdministrator cache = CacheLocator.getCacheAdministrator(); for (final String group : getGroups()) { cache.flushGroup(group); } }

Target:
public void clearCache() { Arrays.asList(getGroups()).forEach(group -> cache.flushGroup(group)); }
Source:
protected ServiceEndpoint<T> configureBasePort(T port, String url, Integer timeout) { ServiceEndpoint<T> serviceEndpoint = new BaseServiceEndpoint<>(port); serviceEndpoint = new URLServiceEndpointDecorator<>(serviceEndpoint, url); serviceEndpoint = new TimeoutServiceEndpointDecorator<>(serviceEndpoint, timeout); boolean isDisableCNCheck = false; try { isDisableCNCheck = PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, DISABLE_CN_CHECK); } catch (PropertyAccessException ex) { LOG.error("Not able to 'disableCNCheck' from the property file: {}", ex.getLocalizedMessage(), ex); } LOG.info("gateway-property--disableCNCheck: '{}'", isDisableCNCheck); if (isDisableCNCheck) { serviceEndpoint = new TLSClientServiceEndpointDecorator<>(serviceEndpoint); } return serviceEndpoint; }

Target:
protected ServiceEndpoint<T> configureBasePort(T port, String url, Integer timeout) { ServiceEndpoint<T> serviceEndpoint = new BaseServiceEndpoint<>(port); serviceEndpoint = new URLServiceEndpointDecorator<>(serviceEndpoint, url); serviceEndpoint = new TimeoutServiceEndpointDecorator<>(serviceEndpoint, timeout); serviceEndpoint = new TLSClientServiceEndpointDecorator<>(serviceEndpoint); return serviceEndpoint; }
Source:
protected T doCreateAggregate(String aggregateIdentifier, DomainEventMessage firstEvent) { return aggregateModel.type(firstEvent.getType()) .map(this::newInstance) .orElseThrow(() -> new IncompatibleAggregateException(format( "The [%s] aggregate does not exist.", firstEvent.getType()))); }

Target:
protected T doCreateAggregate(String aggregateIdentifier, DomainEventMessage firstEvent) { Class<?> type = aggregateModel().type(firstEvent.getType()) .orElse(getAggregateType()); return newInstance(type, constructors.get(type)); }
Source:
private Collection<String> getKeywords() { List<String> klist = new ArrayList<>(); klist.addAll(Arrays.asList(SQLKeywords.keywords)); for (String db: client.getAllDatabaseNames()) { klist.add(db); klist.addAll(client.getTableList(db)); } return klist; }

Target:
private Collection<String> getKeywords() { Stream<String> tokens = Arrays.stream(SQLLexer.tokenNames); Stream<String> rules = Arrays.stream(SQLLexer.ruleNames); List<String> keywords = Stream.concat(tokens, rules) .filter((str) -> str.matches("[A-Z_]+") && str.length() > 1) .distinct() .map(String::toLowerCase) .collect(Collectors.toList()); for (String db: client.getAllDatabaseNames()) { keywords.add(db); keywords.addAll(client.getTableList(db)); } tokens.close(); rules.close(); return keywords; }
Source:
public VirtualConsole(@Assisted Element parent, final Preferences prefs) { prefs_ = prefs; parent_ = parent; if (prefs_.limitConsoleVisible() && parent_ != null && !VirtualConsole.virtualScrollerInitialized_ && !VirtualConsole.loadingVirtualScroller_) { VirtualConsole.loadingVirtualScroller_ = true; virtualScrollerLoader_.addCallback(() -> { try { virtualScrollerNative_ = new VirtualScrollerNative(); virtualScrollerNative_.setup(parent_); VirtualConsole.virtualScrollerInitialized_ = true; VirtualConsole.loadingVirtualScroller_ = false; } catch (JavaScriptException e) { Debug.log(e.getMessage()); } }); } }

Target:
public VirtualConsole(@Assisted Element parent, final Preferences prefs) { prefs_ = prefs; parent_ = parent; VirtualScrollerManager.init(); }
Source:
public void setSuccessActionStatus(int successActionStatus) throws InvalidArgumentException { if (!(successActionStatus == 200 || successActionStatus == 201 || successActionStatus == 204)) { throw new InvalidArgumentException("Success action status accepts the values as 200, 201, or " + "204 (the default) only"); } this.successActionStatus = successActionStatus; }

Target:
public void setSuccessActionStatus(int successActionStatus) throws InvalidArgumentException { if (!(successActionStatus == SuccessActionStatus.SuccessActionStatus200.getValue() || successActionStatus == SuccessActionStatus.SuccessActionStatus201.getValue() || successActionStatus == SuccessActionStatus.SuccessActionStatus204.getValue())) { throw new InvalidArgumentException("Invalid action status, acceptable values are 200, 201, or 204"); } this.successActionStatus = successActionStatus; }
Source:
private Properties getNodeConf(String node) { try { String homeDir = InstancedConfiguration.defaults().get(PropertyKey.HOME); String remoteCommand = String.format( "%s/bin/alluxio getConf", homeDir); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; Properties properties = new Properties(); Process process = Runtime.getRuntime().exec(command); properties.load(process.getInputStream()); return properties; } catch (IOException e) { System.err.format("Unable to retrieve configuration for %s: %s.", node, e.getMessage()); return null; } }

Target:
private Properties getNodeConf(String node) { try { String homeDir = mConf.get(PropertyKey.HOME); String remoteCommand = String.format( "%s/bin/alluxio getConf", homeDir); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = {"bash", "-c", localCommand}; Properties properties = new Properties(); Process process = Runtime.getRuntime().exec(command); properties.load(process.getInputStream()); return properties; } catch (IOException e) { System.err.format("Unable to retrieve configuration for %s: %s.", node, e.getMessage()); return null; } }
Source:
public static <U, V extends U> ValueSupplier<U> supplierOf(final V value) { return new ValueSupplier<U>() { @Override public U value() { return value; } }; }

Target:
public static <V> ValueSupplier<V> supplierOf(final V value) { return new ValueSupplier<V>() { @Override public V value() { return value; } }; }
Source:
public CommandStatus runTimed(long timeout, IRunUtil.IRunnableResult runnable, boolean logErrors) { mInterrupter.checkInterrupted(); RunnableNotifier runThread = new RunnableNotifier(runnable, logErrors); if (logErrors) { if (timeout > 0l) { CLog.d("Running command with timeout: %dms", timeout); } else { CLog.d("Running command without timeout."); } } try { runThread.start(); long startTime = System.currentTimeMillis(); long pollInterval = 0; if (timeout > 0L && timeout < THREAD_JOIN_POLL_INTERVAL) { pollInterval = timeout; } else { pollInterval = THREAD_JOIN_POLL_INTERVAL; } do { try { runThread.join(pollInterval); } catch (InterruptedException e) { if (isInterruptAllowed()) { CLog.i("runTimed: interrupted while joining the runnable"); break; } else { CLog.i( "runTimed: received an interrupt but uninterruptible mode, ignoring"); } } mInterrupter.checkInterrupted(); } while ((timeout == 0L || (System.currentTimeMillis() - startTime) < timeout) && runThread.isAlive()); CommandStatus status = runThread.getStatus(); if (CommandStatus.TIMED_OUT.equals(status) || CommandStatus.EXCEPTION.equals(status)) { CLog.i("runTimed: Calling interrupt, status is %s", status); runThread.cancel(); } mInterrupter.checkInterrupted(); return status; } catch (RunInterruptedException e) { runThread.cancel(); throw e; } }

Target:
public CommandStatus runTimed(long timeout, IRunUtil.IRunnableResult runnable, boolean logErrors) { mInterrupter.checkInterrupted(); RunnableNotifier runThread = new RunnableNotifier(runnable, logErrors); if (logErrors) { if (timeout > 0l) { CLog.d("Running command with timeout: %dms", timeout); } else { CLog.d("Running command without timeout."); } } try { runThread.start(); long startTime = System.currentTimeMillis(); long pollInterval = 0; if (timeout > 0L && timeout < THREAD_JOIN_POLL_INTERVAL) { pollInterval = timeout; } else { pollInterval = THREAD_JOIN_POLL_INTERVAL; } do { try { runThread.join(pollInterval); } catch (InterruptedException e) { if (isInterruptAllowed()) { CLog.i("runTimed: interrupted while joining the runnable"); break; } else { CLog.i("runTimed: currently uninterruptible, ignoring interrupt"); } } mInterrupter.checkInterrupted(); } while ((timeout == 0L || (System.currentTimeMillis() - startTime) < timeout) && runThread.isAlive()); CommandStatus status = runThread.getStatus(); if (CommandStatus.TIMED_OUT.equals(status) || CommandStatus.EXCEPTION.equals(status)) { CLog.i("runTimed: Calling interrupt, status is %s", status); runThread.cancel(); } mInterrupter.checkInterrupted(); return status; } catch (RunInterruptedException e) { runThread.cancel(); throw e; } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (!super.onOptionsItemSelected(item)) { if (item.getItemId() == R.id.clear_history_item) { DBWriter.clearDownloadLog(); return true; } return false; } else { return true; } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (!super.onOptionsItemSelected(item)) { switch (item.getItemId()) { case R.id.clear_history_item: DBWriter.clearDownloadLog(); return true; default: return false; } } else { return true; } }
Source:
public void deleteBucket(String name) throws RepoException { Lock writeLock = this.rwLocks.get(name).writeLock(); writeLock.lock(); boolean rollback = false; Bucket bucket = new Bucket(name); try { sqlService.getConnection(); if (sqlService.getBucket(name) == null) throw new RepoException(RepoException.Type.BucketNotFound); if (Boolean.FALSE.equals(objectStore.bucketExists(bucket))) throw new RepoException("Bucket exists in database but not in object store: " + name); if (sqlService.listObjects(name, 0, 1, true, false, null).size() != 0) throw new RepoException(RepoException.Type.CantDeleteNonEmptyBucket); rollback = true; if (sqlService.removeBucketContent(name) == 0) throw new RepoException("Unable to delete bucket in database: " + name); if (Boolean.FALSE.equals(objectStore.deleteBucket(bucket))) throw new RepoException("Unable to delete bucket in object store: " + name); sqlService.transactionCommit(); rollback = false; } catch (SQLException e) { throw new RepoException(e); } finally { if (rollback) { sqlRollback("bucket " + name); objectStore.createBucket(bucket); } sqlReleaseConnection(); writeLock.unlock(); } }

Target:
public void deleteBucket(String name) throws RepoException { Lock writeLock = this.rwLocks.get(name).writeLock(); writeLock.lock(); boolean rollback = false; boolean bucketDeletion = false; Bucket bucket = new Bucket(name); try { sqlService.getConnection(); rollback = true; if (sqlService.getBucket(name) == null) throw new RepoException(RepoException.Type.BucketNotFound); if (Boolean.FALSE.equals(objectStore.bucketExists(bucket))) throw new RepoException("Bucket exists in database but not in object store: " + name); if (sqlService.listObjects(name, 0, 1, true, false, null).size() != 0) throw new RepoException(RepoException.Type.CantDeleteNonEmptyBucket); if (sqlService.removeBucketContent(name) == 0) throw new RepoException("Unable to delete bucket in database: " + name); bucketDeletion = objectStore.deleteBucket(bucket); if (!bucketDeletion){ throw new RepoException("Unable to delete bucket in object store: " + name); } sqlService.transactionCommit(); rollback = false; } catch (SQLException e) { throw new RepoException(e); } finally { if (rollback) { sqlRollback("bucket " + name); if (bucketDeletion) { objectStore.createBucket(bucket); } } sqlReleaseConnection(); writeLock.unlock(); } }
Source:
public ReportableEntityHandler getHandler(HandlerKey handlerKey) { return handlers.computeIfAbsent(handlerKey, k -> { switch (handlerKey.getEntityType()) { case POINT: return new ReportPointHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig, false, true); case DELTA_COUNTER: return new DeltaCounterHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig, ReportableEntityType.DELTA_COUNTER, true, reportIntervalSeconds); case HISTOGRAM: return new ReportPointHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig, true, true); case SOURCE_TAG: return new ReportSourceTagHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, SOURCE_TAGS_NUM_THREADS)); case TRACE: return new SpanHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig); case TRACE_SPAN_LOGS: return new SpanLogsHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads)); default: throw new IllegalArgumentException("Unexpected entity type " + handlerKey.getEntityType().name() + " for " + handlerKey.getHandle()); } }); }

Target:
public ReportableEntityHandler getHandler(HandlerKey handlerKey) { return handlers.computeIfAbsent(handlerKey, k -> { switch (handlerKey.getEntityType()) { case POINT: return new ReportPointHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig, false, true); case HISTOGRAM: return new ReportPointHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig, true, true); case SOURCE_TAG: return new ReportSourceTagHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, SOURCE_TAGS_NUM_THREADS)); case TRACE: return new SpanHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads), validationConfig); case TRACE_SPAN_LOGS: return new SpanLogsHandlerImpl(handlerKey.getHandle(), blockedItemsPerBatch, senderTaskFactory.createSenderTasks(handlerKey, defaultFlushThreads)); default: throw new IllegalArgumentException("Unexpected entity type " + handlerKey.getEntityType().name() + " for " + handlerKey.getHandle()); } }); }
Source:
public static boolean skipMd5CheckPerRequest(AmazonWebServiceRequest request) { if (System.getProperty("com.amazonaws.services.s3.disableGetObjectMD5Validation") != null) { return true; } if (request instanceof GetObjectRequest) { final GetObjectRequest getObjectRequest = (GetObjectRequest) request; if (getObjectRequest.getRange() != null) { return true; } if (getObjectRequest.getSSECustomerKey() != null) { return true; } } else if (request instanceof PutObjectRequest) { final PutObjectRequest putObjectRequest = (PutObjectRequest) request; final ObjectMetadata om = putObjectRequest.getMetadata(); if (om != null && om.getSSEAlgorithm() != null) { return true; } if (putObjectRequest.getSSECustomerKey() != null) { return true; } if (putObjectRequest.getSSEAwsKeyManagementParams() != null && putObjectRequest.getSSEAwsKeyManagementParams().getAwsKmsKeyId() != null) { return true; } } else if (request instanceof UploadPartRequest) { final UploadPartRequest uploadPartRequest = (UploadPartRequest) request; return uploadPartRequest.getSSECustomerKey() != null; } return false; }

Target:
public static boolean skipMd5CheckPerRequest(AmazonWebServiceRequest request) { if (System.getProperty("com.amazonaws.services.s3.disableGetObjectMD5Validation") != null) { return true; } if (request instanceof GetObjectRequest) { final GetObjectRequest getObjectRequest = (GetObjectRequest) request; if (getObjectRequest.getRange() != null) { return true; } if (getObjectRequest.getSSECustomerKey() != null) { return true; } } else if (request instanceof PutObjectRequest) { final PutObjectRequest putObjectRequest = (PutObjectRequest) request; final ObjectMetadata om = putObjectRequest.getMetadata(); if (om != null && om.getSSEAlgorithm() != null) { return true; } if (putObjectRequest.getSSECustomerKey() != null) { return true; } if (putObjectRequest.getSSEAwsKeyManagementParams() != null && (putObjectRequest.getSSEAwsKeyManagementParams().getEncryption() != null || putObjectRequest.getSSEAwsKeyManagementParams().getAwsKmsKeyId() != null)) { return true; } } else if (request instanceof UploadPartRequest) { final UploadPartRequest uploadPartRequest = (UploadPartRequest) request; return uploadPartRequest.getSSECustomerKey() != null; } return false; }
Source:
public void testMultiPutsTimeout() { DELAY_BATCH_MUTATE = 600; Put put1 = new Put(ROW); put1.addColumn(FAMILY, QUALIFIER, VALUE); Put put2 = new Put(ROW); put2.addColumn(FAMILY, QUALIFIER, VALUE); List<Put> puts = new ArrayList<>(); puts.add(put1); puts.add(put2); try { TABLE.batch(puts, new Object[2]); throw new AssertionError("should not reach here"); } catch (Exception e) { Assert.assertTrue( e instanceof RetriesExhaustedException && e.getCause() instanceof RetriesExhaustedException && e.getCause().getCause() instanceof CallTimeoutException); } }

Target:
public void testMultiPutsTimeout() { DELAY_BATCH_MUTATE = 600; Put put1 = new Put(ROW); put1.addColumn(FAMILY, QUALIFIER, VALUE); Put put2 = new Put(ROW); put2.addColumn(FAMILY, QUALIFIER, VALUE); List<Put> puts = new ArrayList<>(); puts.add(put1); puts.add(put2); try { TABLE.batch(puts, new Object[2]); Assert.fail("should not reach here"); } catch (Exception e) { Assert.assertTrue( e instanceof RetriesExhaustedException && e.getCause() instanceof RetriesExhaustedException && e.getCause().getCause() instanceof CallTimeoutException); } }
Source:
public Map<byte[], List<byte[]>> rollWal(long now) throws IOException { this.isRolling = true; try { this.lastRollTime = now; this.rollRequest.set(false); return wal.rollWriter(true); } finally { this.isRolling = false; synchronized (RollController.class) { RollController.class.notifyAll(); } } }

Target:
public Map<byte[], List<byte[]>> rollWal(long now) throws IOException { this.isRolling = true; try { this.lastRollTime = now; this.rollRequest.set(false); return wal.rollWriter(true); } finally { this.isRolling = false; } }
Source:
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; if (SecurityContextHolder.getContext().getAuthentication() == null || SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken) { Authentication auth = Jenkins.ANONYMOUS; String authenticatedUserFromApiToken = getUserFromAuthorizationHeader(request); String userName = authenticatedUserFromApiToken == null ? getUserFromReverseProxyHeader(request) : authenticatedUserFromApiToken; if (userName != null) { try { UserDetails userDetails = activeDirectorySecurityRealm.getAuthenticationProvider().loadUserByUsername(userName); GrantedAuthority[] authorities = userDetails.getAuthorities(); auth = new UsernamePasswordAuthenticationToken(userName, "", authorities); } catch (UsernameNotFoundException e) { LOGGER.log(Level.FINE, "User from HTTP Header {0} not found in LDAP", userName); } } SecurityContextHolder.getContext().setAuthentication(auth); } chain.doFilter(request, response); }

Target:
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; if (Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken) { String authenticatedUserFromApiToken = getUserFromAuthorizationHeader(request); String userName = authenticatedUserFromApiToken == null ? getUserFromReverseProxyHeader(request) : authenticatedUserFromApiToken; if (userName != null) { try { UserDetails userDetails = activeDirectorySecurityRealm.getAuthenticationProvider().loadUserByUsername(userName); GrantedAuthority[] authorities = userDetails.getAuthorities(); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userName, "", authorities); try (ACLContext _ = ACL.as(auth)) { chain.doFilter(request, response); } return; } catch (UsernameNotFoundException e) { LOGGER.log(Level.FINE, "User from HTTP Header {0} not found in LDAP", userName); } } } chain.doFilter(request, response); }
Source:
CommitUpdate getCommitUpdate(long startTs) { try { return lockWatchEventCache.getCommitUpdate(startTs); } catch (LockWatchFailedException e) { throw new TransactionLockWatchFailedException("Failed to get commit update", e); } }

Target:
CommitUpdate getCommitUpdate(long startTs) { return lockWatchEventCache.getCommitUpdate(startTs); }
Source:
public SavedPageTimestampCheckService() { super("SavedPageSyncService"); setIntentRedelivery(true); }

Target:
public SavedPageTimestampCheckService() { super("SavedPageTimestampCheckService"); setIntentRedelivery(true); }
Source:
public String loginUser( String username, String password) throws IOException, JSONException { if(username == null || username.isEmpty() || password == null || password.isEmpty()) throw new IOException("invalid input of username or password"); final String url = URL_AUTH + "/" + URL_LOGIN; final JSONObject user = new JSONObject(); user.put("username", username); user.put("password", password); Map<String, String> response = request(url, user, null, HTTP_METHOD_POST); int result = checkResponseCode(response.get(RESPONSE_CODE), "login"); String session_id = response.get("session-id"); if (result != 0 && session_id == null) { Log.w(TAG, "CommonSense login failed: no session id received!"); throw new IOException("login failed with no session id"); } return session_id; }

Target:
public String loginUser( String username, String password) throws IOException, RuntimeException { if(username == null || username.isEmpty() || password == null || password.isEmpty()) throw new IllegalArgumentException("invalid input of username or password"); final String url = URL_AUTH + "/" + URL_LOGIN; final JSONObject user = new JSONObject(); try { user.put("username", username); user.put("password", password); }catch(JSONException JS){ throw new RuntimeException("loginUser failed to create the content for the request"); } Map<String, String> response = request(url, user, null, HTTP_METHOD_POST); int result = checkResponseCode(response.get(RESPONSE_CODE), "login"); if(result != 0) throw new IOException("failed to log in, response code is:" + response.get(RESPONSE_CODE)); String session_id = response.get("session-id"); if (session_id == null) Log.w(TAG, "loginUser returns a null session id"); return session_id; }
Source:
public static long Add0(long arg) { if (doThrow) { throw new Error(); } return 0 + arg; }

Target:
public static long $noinline$Add0(long arg) { if (doThrow) { throw new Error(); } return 0 + arg; }