auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private SimpleDigestPassword createSimpleDigestPasswordTable(String algorithm, String userName, String userPassword) throws Exception { Connection connection = null; Statement statement = null; PreparedStatement preparedStatement = null; try { connection = this.dataSource.getConnection(); statement = connection.createStatement(); statement.executeUpdate("DROP TABLE IF EXISTS user_simple_digest_password"); statement.executeUpdate("CREATE TABLE user_simple_digest_password ( id INTEGER IDENTITY, name VARCHAR(100), digest OTHER)"); EncryptablePasswordSpec eps = new EncryptablePasswordSpec(userPassword.toCharArray(), null); PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm); SimpleDigestPassword tsdp = (SimpleDigestPassword) passwordFactory.generatePassword(eps); preparedStatement = connection.prepareStatement("INSERT INTO user_simple_digest_password (name, digest) VALUES (?, ?)"); preparedStatement.setString(1, userName); preparedStatement.setBytes(2, tsdp.getDigest()); preparedStatement.execute(); return tsdp; } finally { safeClose(preparedStatement); safeClose(statement); safeClose(connection); } }

Target:
private SimpleDigestPassword createSimpleDigestPasswordTable(String algorithm, String userName, String userPassword) throws Exception { try ( Connection connection = this.dataSource.getConnection(); Statement statement = connection.createStatement(); ) { statement.executeUpdate("DROP TABLE IF EXISTS user_simple_digest_password"); statement.executeUpdate("CREATE TABLE user_simple_digest_password ( id INTEGER IDENTITY, name VARCHAR(100), digest OTHER)"); } try ( Connection connection = this.dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO user_simple_digest_password (name, digest) VALUES (?, ?)"); ) { EncryptablePasswordSpec eps = new EncryptablePasswordSpec(userPassword.toCharArray(), null); PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm); SimpleDigestPassword tsdp = (SimpleDigestPassword) passwordFactory.generatePassword(eps); preparedStatement.setString(1, userName); preparedStatement.setBytes(2, tsdp.getDigest()); preparedStatement.execute(); return tsdp; } }
Source:
public void returnsAnEmptyResponseBody() throws IOException { new FtRemote( new TkEmpty() ).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .body().set("returnsAnEmptyResponseBody").back() .fetch() .as(RestResponse.class) .assertBody(new IsEqual<>("HTTP/1.1 200 OK\r\n\r\n")) .assertStatus(HttpURLConnection.HTTP_OK); } } ); }

Target:
public void returnsAnEmptyResponseBody() throws IOException { new FtRemote( new TkEmpty() ).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .method("POST") .body().set("returnsAnEmptyResponseBody").back() .fetch() .as(RestResponse.class) .assertBody(new IsEqual<>("")) .assertStatus(HttpURLConnection.HTTP_OK); } } ); }
Source:
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); if (processingRole == null) { processingRole = processRoleStack.peek(); } processRoleStack.push(processingRole); final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); final DitaClass cls = atts.getValue(ATTRIBUTE_NAME_CLASS) != null ? new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS)) : null; classes.addFirst(cls); if (chunkLevel > 0) { chunkLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if (MAP_TOPICREF.matches(classValue)) { parseAttribute(atts); } getContentHandler().startElement(uri, localName, qName, atts); }

Target:
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { String processingRole = atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE); if (processingRole == null) { processingRole = processRoleStack.peek(); } processRoleStack.push(processingRole); final String classValue = atts.getValue(ATTRIBUTE_NAME_CLASS); final DitaClass cls = atts.getValue(ATTRIBUTE_NAME_CLASS) != null ? new DitaClass(atts.getValue(ATTRIBUTE_NAME_CLASS)) : new DitaClass(""); if (cls.isValid()) { classes.addFirst(cls); }else { classes.addFirst(null); } if (chunkLevel > 0) { chunkLevel++; } else if (atts.getValue(ATTRIBUTE_NAME_CHUNK) != null) { chunkLevel++; } if (MAP_TOPICREF.matches(classValue)) { parseAttribute(atts); } getContentHandler().startElement(uri, localName, qName, atts); }
Source:
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { Any23Parser parser = null; try { String htmlContent = new String(content.getContent(), Charset.forName("UTF-8")); parser = new Any23Parser(content.getUrl(), htmlContent); } catch (TripleHandlerException e) { throw new RuntimeException("Error running Any23 parser: " + e.getMessage()); } Set<String> triples = parser.getTriples(); StringBuilder sb = new StringBuilder(); Parse parse = parseResult.get(content.getUrl()); Metadata metadata = parse.getData().getParseMeta(); for (String triple : triples) { sb.append(triple); sb.append("\t"); } metadata.add(ANY23_TRIPLES, sb.toString()); return parseResult; }

Target:
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { String[] extractorNames = conf.getStrings(ANY_23_EXTRACTORS_CONF,"html-head-meta"); Any23Parser parser; try { String htmlContent = new String(content.getContent(), Charset.forName("UTF-8")); parser = new Any23Parser(content.getUrl(), htmlContent, extractorNames); } catch (TripleHandlerException e) { throw new RuntimeException("Error running Any23 parser: " + e.getMessage()); } Set<String> triples = parser.getTriples(); Parse parse = parseResult.get(content.getUrl()); Metadata metadata = parse.getData().getParseMeta(); for (String triple : triples) { metadata.add(ANY23_TRIPLES, triple); } return parseResult; }
Source:
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { if (DISABLE) { return; } String imageId = record.getImageId(); Fingerprint f = forImage(run, imageId); synchronized (f) { Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); DockerFingerprintAction.addToRun(f, imageId, run); bc.commit(); } finally { bc.abort(); } } }

Target:
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException { if (DISABLE) { LOGGER.info("Recording of fingerprints is disabled, no RUN fingerprint record will be made."); return; } String imageId = record.getImageId(); Fingerprint f = forImage(run, imageId); synchronized (f) { Collection<FingerprintFacet> facets = f.getFacets(); DockerRunFingerprintFacet runFacet = null; for (FingerprintFacet facet : facets) { if (facet instanceof DockerRunFingerprintFacet) { runFacet = (DockerRunFingerprintFacet) facet; break; } } BulkChange bc = new BulkChange(f); try { if (runFacet == null) { runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId); facets.add(runFacet); } runFacet.add(record); runFacet.addFor(run); DockerFingerprintAction.addToRun(f, imageId, run); bc.commit(); } finally { bc.abort(); } } }
Source:
public void myDiffPreferences(AsyncCallback<AccountDiffPreference> callback) { run(callback, new Action<AccountDiffPreference>() { @Override public AccountDiffPreference run(ReviewDb db) throws OrmException, Failure, NoSuchProjectException, NoSuchGroupException { return db.accountDiffPreferences().get(currentUser.get().getAccountId()); } }); }

Target:
public void myDiffPreferences(AsyncCallback<AccountDiffPreference> callback) { run(callback, new Action<AccountDiffPreference>() { @Override public AccountDiffPreference run(ReviewDb db) throws OrmException { return currentUser.get().getAccountDiffPreference(); } }); }
Source:
protected PropertyValue getSplitTaskExecutorPropertyValue(BeanDefinitionRegistry beanDefinitionRegistry) { PropertyValue propertyValue; if (hasBeanDefinition(beanDefinitionRegistry, JSR_352_SPLIT_TASK_EXECUTOR_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new RuntimeBeanReference(JSR_352_SPLIT_TASK_EXECUTOR_NAME)); } else if (hasBeanDefinition(beanDefinitionRegistry, TASK_EXECUTOR_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new RuntimeBeanReference(TASK_EXECUTOR_NAME)); } else { propertyValue = new PropertyValue(TASK_EXECUTOR_NAME, new SimpleAsyncTaskExecutor()); } return propertyValue; }

Target:
protected PropertyValue getSplitTaskExecutorPropertyValue(BeanDefinitionRegistry beanDefinitionRegistry) { PropertyValue propertyValue; if (hasBeanDefinition(beanDefinitionRegistry, JSR_352_SPLIT_TASK_EXECUTOR_BEAN_NAME)) { propertyValue = new PropertyValue(TASK_EXECUTOR_PROPERTY_NAME, new RuntimeBeanReference(JSR_352_SPLIT_TASK_EXECUTOR_BEAN_NAME)); } else { propertyValue = new PropertyValue(TASK_EXECUTOR_PROPERTY_NAME, new SimpleAsyncTaskExecutor()); } return propertyValue; }
Source:
void subscribersOf() { ImmutableSet<SubscriberMethod> methods = subscriberClass.subscribersOf( EventClass.from(SpeakerJoined.class), EmptyClass.instance()); assertThat(methods).hasSize(1); SubscriberMethod actual = methods.asList() .get(0); assertThat(actual.rawMethod()) .isEqualTo(getMethod(ConferenceProgram.class, "addSpeaker")); }

Target:
void subscribersOf() { ImmutableSet<SubscriberMethod> methods = subscriberClass.subscribersOf( EventClass.from(SpeakerJoined.class), EmptyClass.instance()); assertThat(methods).hasSize(1); SubscriberMethod actual = getFirst(methods, null); assertThat(actual.rawMethod()) .isEqualTo(getMethod(ConferenceProgram.class, "addSpeaker")); }
Source:
public List<InfoInsightCards> getGenericInsightCards( @Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("category") final String value) { try { final InsightCard.Category category = InsightCard.Category.fromString(value); final List<InfoInsightCards> cards = trendsInsightsDAO.getGenericInsightCardsByCategory(category.toString().toLowerCase()); final DateTime readDate = DateTime.now(DateTimeZone.UTC).plusDays(1); LOGGER.debug("action=insight_detail account_id={} category={} readdate={}", accessToken.accountId, category, readDate); return cards; } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }

Target:
public List<InfoInsightCards> getGenericInsightCards( @Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("category") final String value) { try { final InsightCard.Category category = InsightCard.Category.fromString(value); final List<InfoInsightCards> cards = trendsInsightsDAO.getGenericInsightCardsByCategory(category.toString().toLowerCase()); final DateTime readDate = DateTime.now(DateTimeZone.UTC); LOGGER.debug("action=insight_detail account_id={} category={} readdate={}", accessToken.accountId, category, readDate); return cards; } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } }
Source:
private void runTestPreservePath(Boolean preservePathOnForward) throws Exception { setPreservePathOnForward(preservePathOnForward); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url.toString() + "/test?path="+ URLEncoder.encode(tempDir)); HttpResponse response = httpclient.execute(httpget); long end = System.currentTimeMillis() + TIMEOUT; File file = new File(tempDir + "/output.txt"); while (!file.exists() && System.currentTimeMillis() < end) { Thread.sleep(100); } Assert.assertTrue(file + " was not created within the timeout", file.exists()); final String expectedServletPath; final String expectedRequestURL; if (preservePathOnForward != null && preservePathOnForward) { expectedServletPath = "/test"; expectedRequestURL = url + "/test"; } else{ expectedServletPath = "/preserve-path.jsp"; expectedRequestURL = url + "preserve-path.jsp"; } final String expectedRequestURI = new URL(expectedRequestURL).getPath(); try (BufferedReader r = new BufferedReader(new FileReader(file))) { String servletPath = r.readLine(); Assert.assertEquals("servletPath: " + expectedServletPath, servletPath); String requestUrl = r.readLine(); Assert.assertEquals("requestUrl: " + expectedRequestURL, requestUrl); String requestUri = r.readLine(); Assert.assertEquals("requestUri: " + expectedRequestURI, requestUri); } }

Target:
private void runTestPreservePath(Boolean preservePathOnForward) throws Exception { setPreservePathOnForward(preservePathOnForward); HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url.toString() + "/test?path="+ URLEncoder.encode(tempDir)); HttpResponse response = httpclient.execute(httpget); long end = System.currentTimeMillis() + TIMEOUT; File file = new File(tempDir + "/output.txt"); while ((!file.exists() || file.length() == 0) && System.currentTimeMillis() < end) { Thread.sleep(100); } Assert.assertTrue(file + " was not created within the timeout", file.exists()); Assert.assertTrue(file + " is empty", file.length() > 0); final String expectedServletPath; final String expectedRequestURL; if (preservePathOnForward != null && preservePathOnForward) { expectedServletPath = "/test"; expectedRequestURL = url + "/test"; } else{ expectedServletPath = "/preserve-path.jsp"; expectedRequestURL = url + "preserve-path.jsp"; } final String expectedRequestURI = new URL(expectedRequestURL).getPath(); try (BufferedReader r = new BufferedReader(new FileReader(file))) { String servletPath = r.readLine(); Assert.assertEquals("servletPath: " + expectedServletPath, servletPath); String requestUrl = r.readLine(); Assert.assertEquals("requestUrl: " + expectedRequestURL, requestUrl); String requestUri = r.readLine(); Assert.assertEquals("requestUri: " + expectedRequestURI, requestUri); } }
Source:
public void stop() throws InterruptedException { if (containerId.isPresent()) { try { docker.stopContainer(containerId.get(), SECONDS_TO_WAIT_BEFORE_KILL); } catch (DockerException e) { log.warn("Stopping image failed", containerId.get(), e); } } }

Target:
public void stop() throws InterruptedException { if (containerId.isPresent()) { final String container = containerId.get(); stopAsync().awaitTerminated(); try { docker.stopContainer(container, SECONDS_TO_WAIT_BEFORE_KILL); } catch (DockerException e) { log.warn("Stopping container failed", container, e); } } }
Source:
public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { final BucketResult result = resultsIterator.next(); DoubleType.DOUBLE.writeDouble( entryBuilder, result.threshold); } out.closeEntry(); }

Target:
public static void output(@AggregationState PrecisionRecallState state, BlockBuilder out) { Iterator<BucketResult> resultsIterator = getResultsIterator(state); BlockBuilder entryBuilder = out.beginBlockEntry(); while (resultsIterator.hasNext()) { BucketResult result = resultsIterator.next(); DoubleType.DOUBLE.writeDouble( entryBuilder, result.getThreshold()); } out.closeEntry(); }
Source:
public Optional<? extends Style> loadStyle(final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, final String styleString) { if (styleString != null) { for (StyleParserPlugin plugin : this.plugins) { try { Optional<? extends Style> style = plugin.parseStyle( configuration, clientHttpRequestFactory, styleString); if (style.isPresent()) { if (LOGGER.isDebugEnabled()) { try { final SLDTransformer transformer = new SLDTransformer(); final StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); final UserLayer userLayer = styleFactory.createUserLayer(); userLayer.addUserStyle(style.get()); final StyledLayerDescriptor sld = styleFactory.createStyledLayerDescriptor(); sld.addStyledLayer(userLayer); LOGGER.debug("Loaded style from: \n\n '{}': \n\n{}", styleString, transformer.transform(sld)); } catch (Exception e) { LOGGER.debug(String.format("Loaded style from: \n\n '%s' \n\n<Unable to " + "transform it to xml>: %s", styleString, e), e); } } return style; } } catch (Throwable t) { throw ExceptionUtils.getRuntimeException(t); } } } return Optional.absent(); }

Target:
public Optional<? extends Style> loadStyle(final Configuration configuration, @Nonnull final ClientHttpRequestFactory clientHttpRequestFactory, final String styleString) { if (styleString != null) { for (StyleParserPlugin plugin : this.plugins) { try { Optional<? extends Style> style = plugin.parseStyle( configuration, clientHttpRequestFactory, styleString); if (style.isPresent()) { if (LOGGER.isDebugEnabled()) { try { final SLDTransformer transformer = new SLDTransformer(); final StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); final UserLayer userLayer = styleFactory.createUserLayer(); userLayer.addUserStyle(style.get()); final StyledLayerDescriptor sld = styleFactory.createStyledLayerDescriptor(); sld.addStyledLayer(userLayer); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Loaded style from: \n\n '{}': \n\n{}", styleString, transformer.transform(sld)); } } catch (Exception e) { LOGGER.debug(String.format("Loaded style from: \n\n '%s' \n\n<Unable to " + "transform it to xml>: %s", styleString, e), e); } } return style; } } catch (Throwable t) { throw ExceptionUtils.getRuntimeException(t); } } } return Optional.absent(); }
Source:
private String getMissingInherritNamespaces(final String text) { if (text == null) { return ""; } final String namespaces = getNamespacesFromNamespaceToken(text); final String[] containedNamespaces = namespaces == null ? new String[0] : namespaces.split(" "); final StringBuilder sb = new StringBuilder(); boolean first = true; for (String rn : rootTokenNamespaces) { boolean nsExists = false; for (String cn : containedNamespaces) { if (rn.equals(cn)) { nsExists = true; first = false; break; } } if (!nsExists) { sb.append(first ? rn : " " + rn); first = false; } } return sb.toString(); }

Target:
private String getMissingInherritNamespaces(final String text) { final StringBuilder sb = new StringBuilder(); if (text != null) { boolean first = true; final String[] containedNamespaces = getNamespacesFromNamespaceTokenSplitter(text); for (final String rn : rootTokenNamespaces) { boolean nsExists = false; for (final String cn : containedNamespaces) { if (rn.equals(cn)) { nsExists = true; if (first) { first = false; } break; } } if (!nsExists) { sb.append(first ? rn : NAMESPACE_SEPERATOR + rn); if (first) { first = false; } } } } return sb.toString(); }
Source:
public KeyValuePairValidation() { this.allowAlsoKey = false; }

Target:
public KeyValuePairValidation() { this(false); }
Source:
public void setActive(boolean isActive) { if (!isActive) { logger.debug(Thread.currentThread().getStackTrace().toString()); } this.isActive = isActive; }

Target:
public void setActive(boolean isActive)
Source:
public void testCacheUsesCacheManagerClassLoaderForDefaultURI() { CachingProvider cachingProvider = Caching.getCachingProvider(); LimitedClassLoader limitedClassLoader = new LimitedClassLoader(cachingProvider.getDefaultClassLoader()); CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), limitedClassLoader); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<Object, Object>().setStoreByValue(true); Cache<Object, Object> cache = cacheManager.createCache("test", configuration); cache.put(1L, new Customer(1L)); try { cache.get(1L); fail("Expected AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), is("No com.pany here")); } }

Target:
public void testCacheUsesCacheManagerClassLoaderForDefaultURI() { CachingProvider cachingProvider = Caching.getCachingProvider(); LimitedClassLoader limitedClassLoader = new LimitedClassLoader(cachingProvider.getDefaultClassLoader()); CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), limitedClassLoader); MutableConfiguration<Object, Object> configuration = new MutableConfiguration<Object, Object>(); Cache<Object, Object> cache = cacheManager.createCache("test", configuration); cache.put(1L, new Customer(1L)); try { cache.get(1L); fail("Expected AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), is("No com.pany here")); } }
Source:
public CompletableFuture<Void> unlock() { log.tracef("unlock called from %s", originator); CompletableFuture<Void> unlockRequest = new CompletableFuture<>(); if (isChangeViewUnlockInProgress()) { pendingUnlocks.offer(new UnlockRequestHolder(originator, unlockRequest)); } else { readWriteMap.eval(lockKey, new UnlockFunction(originator)).whenComplete((unlockResult, ex) -> { if (ex == null) { log.tracef("Unlock result for %s is %b", originator, unlockResult); unlockRequest.complete(null); } else { unlockRequest.completeExceptionally(handleException(ex)); } }); } return unlockRequest; }

Target:
public CompletableFuture<Void> unlock() { log.tracef("unlock called from %s", originator); CompletableFuture<Void> unlockRequest = new CompletableFuture<>(); readWriteMap.eval(lockKey, new UnlockFunction(originator)).whenComplete((unlockResult, ex) -> { if (ex == null) { log.tracef("Unlock result for %s is %b", originator, unlockResult); unlockRequest.complete(null); } else { unlockRequest.completeExceptionally(handleException(ex)); } }); return unlockRequest; }
Source:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this.provider = new RemotableSVNAuthenticationBuilderProvider(credentials, Collections.<String, Credentials>emptyMap(), TaskListener.NULL); }

Target:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this(credentials, null, TaskListener.NULL); }
Source:
public void incorrectBackupDirectory() throws IOException { Path backupDirectoryResolved = new File( "." ).toPath().toRealPath().resolve( "non_existing_dir" ); String output = runBackup( "--backup-dir=non_existing_dir", "--name=mybackup" ); String reason = String.format( "command failed: Directory '%s' does not exist.\n", backupDirectoryResolved.toFile().toString() ); assertEquals( reason, output ); }

Target:
public void incorrectBackupDirectory() throws IOException { Path backupDirectoryResolved = HERE.toRealPath().resolve( "non_existing_dir" ); String output = runBackup( "--backup-dir=non_existing_dir", "--name=mybackup" ); String reason = String.format( "command failed: Directory '%s' does not exist.\n", backupDirectoryResolved ); assertThat( output, containsString( reason ) ); }
Source:
@Test public void setsCustomName() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { ctx.log().addListener(log::set, RequestLogAvailability.COMPLETE); return client.execute(ctx, req); }) .build()); http.newCall(REQUEST, BodyConverters.NULL, "custom-name").execute(); await().untilAsserted(() -> assertThat(log).doesNotHaveValue(null)); assertThat(log.get().requestContent()).isInstanceOfSatisfying(RpcRequest.class, req -> assertThat(req.method().endsWith("custom-name"))); }

Target:
@Test public void setsCustomName() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { ctx.log().addListener(log::set, RequestLogAvailability.COMPLETE); return client.execute(ctx, req); }) .build()); http.newCall(REQUEST, BodyConverters.NULL, "custom-name").execute(); await().untilAsserted(() -> assertThat(log).doesNotHaveValue(null)); assertThat(log.get().context().attr(HttpCall.NAME).get()) .isEqualTo("custom-name"); }
Source:
private String calcExternalNetworkName(int index) { boolean multiple = clustersByProvider.keySet().size() > 1; String indexSuffix = multiple ? MessageFormat.format(MULTIPLE_PROVIDERS, index + 1) : ""; String externalNetworkName = getNetwork().getName(); int newNetworkNameLength = getNetwork().getName().length() + EXTERNAL_PREFIX.length() + indexSuffix.length(); if (newNetworkNameLength > BusinessEntitiesDefinitions.NETWORK_NAME_SIZE) { externalNetworkName = externalNetworkName.substring(0, 2 * BusinessEntitiesDefinitions.NETWORK_NAME_SIZE - newNetworkNameLength); } return MessageFormat.format(EXTERNAL_NAME, EXTERNAL_PREFIX, externalNetworkName, indexSuffix); }

Target:
private String calcExternalNetworkName(int index) { boolean multiple = clustersByProvider.keySet().size() > 1; String indexSuffix = multiple ? MessageFormat.format(MULTIPLE_PROVIDERS, index + 1) : ""; String externalNetworkName = getNetwork().getName(); int newNetworkNameLength = getNetwork().getName().length() + EXTERNAL_PREFIX.length() + indexSuffix.length(); if (newNetworkNameLength > BusinessEntitiesDefinitions.NETWORK_NAME_SIZE) { externalNetworkName = externalNetworkName.substring(0, BusinessEntitiesDefinitions.NETWORK_NAME_SIZE - EXTERNAL_PREFIX.length() - indexSuffix.length()); } return MessageFormat.format(EXTERNAL_NAME, EXTERNAL_PREFIX, externalNetworkName, indexSuffix); }
Source:
public List<DataPartition> findMatchingPartitions(FileFilter filter) { if (dataPartitionRanges.size() == 0) { return Arrays.asList(dataPartitions); } CompiledFileFilter compiledFileFilter = null; try { compiledFileFilter = new CompiledFileFilter(this.recordDef,filter); } catch (Exception e) { return Arrays.asList(dataPartitions); } ArrayList<DataPartition> matchingPartitions = new ArrayList<DataPartition>(); for (int i = 0; i < dataPartitionRanges.size(); i++) { DataPartitionRecordRange partitionRange = dataPartitionRanges.get(i); if (compiledFileFilter.partitionMatchesFilter(partitionRange)) { matchingPartitions.add(partitionRange.dataPartition); } } return matchingPartitions; }

Target:
public List<DataPartition> findMatchingPartitions(FileFilter filter) { if (dataPartitionRanges.size() == 0 || filter == null) { return Arrays.asList(dataPartitions); } CompiledFileFilter compiledFileFilter = null; try { compiledFileFilter = new CompiledFileFilter(this.recordDef,filter); } catch (Exception e) { return Arrays.asList(dataPartitions); } ArrayList<DataPartition> matchingPartitions = new ArrayList<DataPartition>(); for (int i = 0; i < dataPartitionRanges.size(); i++) { DataPartitionRecordRange partitionRange = dataPartitionRanges.get(i); if (compiledFileFilter.partitionMatchesFilter(partitionRange)) { matchingPartitions.add(partitionRange.dataPartition); } } return matchingPartitions; }
Source:
public Iterable<Fork> iterate( @NotNull(message = "sort can't be NULL") final String sort) { return new RtPagination<Fork>( this.request.uri() .queryParam("sort", sort) .back(), new RtPagination.Mapping<Fork>() { @Override public Fork map(final JsonObject object) { return new Fork() { @Override public JsonObject json() throws IOException { return object; } }; } } ); }

Target:
public Iterable<Fork> iterate( @NotNull(message = "sort can't be NULL") final String sort) { return new RtPagination<Fork>( this.request.uri() .queryParam("sort", sort).back(), new RtPagination.Mapping<Fork, JsonObject>() { @Override public Fork map(final JsonObject value) { return new Fork() { @Override public JsonObject json() throws IOException { return value; } @Override public int number() { throw new UnsupportedOperationException(""); } @Override public void patch( final JsonObject json) throws IOException { throw new UnsupportedOperationException(""); } }; } } ); }
Source:
private int getPlaylistId(Resources res) { Uri uri = MediaStore.Audio.Playlists.getContentUri("external"); final String[] ids = new String[] { MediaStore.Audio.Playlists._ID }; final String where = MediaStore.Audio.Playlists.NAME + "=?"; final String[] args = new String[] { res.getString(R.string.audio_db_playlist_name) }; Cursor cursor = query(uri, ids, where, args, null); if (cursor == null) { Log.v(TAG, "query returns null"); } int id = -1; if (cursor != null) { try { cursor.moveToFirst(); if (!cursor.isAfterLast()) { id = cursor.getInt(0); } } finally { cursor.close(); } } return id; }

Target:
private int getPlaylistId(Resources res) { Uri uri = MediaStore.Audio.Playlists.getContentUri("external"); final String[] ids = new String[] { MediaStore.Audio.Playlists._ID }; final String where = MediaStore.Audio.Playlists.NAME + "=?"; final String[] args = new String[] { res.getString(R.string.audio_db_playlist_name) }; Cursor cursor = query(uri, ids, where, args, null); if (cursor == null) { Log.v(TAG, "query returns null"); } int id = -1; if (cursor != null) { try { if (cursor.moveToFirst()) { id = cursor.getInt(0); } } finally { cursor.close(); } } return id; }
Source:
public int getPreferredWidth() { return ComponentConstants.VIDEOPLAYER_PREFERRED_WIDTH; }

Target:
public int getPreferredWidth() { return ComponentConstants.CHART_PREFERRED_WIDTH; }
Source:
public EncryptionKey getEncryptionKey() { EncryptionKey key = null; if (this.manager.keyExists()) { key = this.manager.loadKeyUsingPassword(this.password); } else { key = this.manager.generateAndSaveKeyProtectedByPassword(this.password); } return key; }

Target:
public synchronized EncryptionKey getEncryptionKey() { EncryptionKey key = null; if (this.manager.keyExists()) { key = this.manager.loadKeyUsingPassword(this.password); } else { key = this.manager.generateAndSaveKeyProtectedByPassword(this.password); } return key; }
Source:
private void loadAwards() { File dir = new File(AWARDS_XML_ROOT_PATH); File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); if(files == null) { return; } for(File file : files) { try{ InputStream inputStream = new FileInputStream(file); loadAwardsFromStream(inputStream, file.getName()); inputStream.close(); } catch (IOException e){ MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", e); } } }

Target:
private void loadAwards() { File dir = new File(AWARDS_XML_ROOT_PATH); File[] files = dir.listFiles((dir1, filename) -> filename.endsWith(".xml")); if (files == null) { return; } for (File file : files) { try (InputStream inputStream = new FileInputStream(file)) { loadAwardsFromStream(inputStream, file.getName()); } catch (IOException e){ MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", e); } } }
Source:
public void example48(Vertx vertx) throws CertificateException { SelfSignedCertificate certificate = SelfSignedCertificate.create(); NetServerOptions serverOptions = new NetServerOptions() .setSsl(true) .setKeyCertOptions(certificate.keyCertOption()) .setTrustOptions(certificate.trustOptions()); NetServer server = vertx.createNetServer(serverOptions) .connectHandler(socket -> socket.write("Hello!").end()) .listen(1234, "localhost"); NetClientOptions clientOptions = new NetClientOptions() .setSsl(true) .setKeyCertOptions(certificate.keyCertOption()) .setTrustOptions(certificate.trustOptions()); NetClient client = vertx.createNetClient(clientOptions); client.connect(1234, "localhost", ar -> { if (ar.succeeded()) { ar.result().handler(System.out::println); } else { System.err.println("Woops: " + ar.cause().getMessage()); } }); }

Target:
public void example48(Vertx vertx) throws CertificateException { SelfSignedCertificate certificate = SelfSignedCertificate.create(); NetServerOptions serverOptions = new NetServerOptions() .setSsl(true) .setKeyCertOptions(certificate.keyCertOptions()) .setTrustOptions(certificate.trustOptions()); NetServer server = vertx.createNetServer(serverOptions) .connectHandler(socket -> socket.write("Hello!").end()) .listen(1234, "localhost"); NetClientOptions clientOptions = new NetClientOptions() .setSsl(true) .setKeyCertOptions(certificate.keyCertOptions()) .setTrustOptions(certificate.trustOptions()); NetClient client = vertx.createNetClient(clientOptions); client.connect(1234, "localhost", ar -> { if (ar.succeeded()) { ar.result().handler(buffer -> System.out.println(buffer)); } else { System.err.println("Woops: " + ar.cause().getMessage()); } }); }
Source:
public void update(String body) throws IOException { owner.root.retrieve() .method("POST") .with("body", body) .method("PATCH") .withUrlPath(getApiTail()) .to(GHCommitComment.class); this.body = body; }

Target:
public void update(String body) throws IOException { owner.root.createRequest() .method("PATCH") .with("body", body) .withUrlPath(getApiTail()) .fetch(GHCommitComment.class); this.body = body; }
Source:
public static void setDefaultRetention_test() throws Exception { if (!mintEnv) { System.out.println("Test: setDefaultRetention(String bucketName)"); } long startTime = System.currentTimeMillis(); String bucketName = getRandomName(); try { client.makeBucket(bucketName, null, true); ObjectLockConfiguration config = new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(10)); client.setDefaultRetention(bucketName, config); mintSuccessLog("setDefaultRetention (String bucketName)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog("setDefaultRetention (String bucketName)", null, startTime); } else { mintFailedLog( "setDefaultRetention (String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } finally { client.removeBucket(bucketName); } }

Target:
public static void setDefaultRetention_test() throws Exception { if (!mintEnv) { System.out.println("Test: setDefaultRetention(String bucketName)"); } long startTime = System.currentTimeMillis(); String bucketName = getRandomName(); try { client.makeBucket(bucketName, null, true); try { ObjectLockConfiguration config = new ObjectLockConfiguration(RetentionMode.COMPLIANCE, new RetentionDurationDays(10)); client.setDefaultRetention(bucketName, config); } finally { client.removeBucket(bucketName); } mintSuccessLog("setDefaultRetention (String bucketName)", null, startTime); } catch (Exception e) { ErrorResponse errorResponse = null; if (e instanceof ErrorResponseException) { ErrorResponseException exp = (ErrorResponseException) e; errorResponse = exp.errorResponse(); } if (errorResponse != null && errorResponse.errorCode() == ErrorCode.NOT_IMPLEMENTED) { mintIgnoredLog("setDefaultRetention (String bucketName)", null, startTime); } else { mintFailedLog( "setDefaultRetention (String bucketName)", null, startTime, null, e.toString() + " >>> " + Arrays.toString(e.getStackTrace())); throw e; } } }
Source:
private void maybeAddGoogExport(Node exportsName) { String fullname = providesObjectChildren.keySet().iterator().next(); if ("exports".equals(exportsName.getQualifiedName())) { addExport(exportsName.getQualifiedName(), fullname, nameUtil.lastStepOfName(fullname)); } else if (exportsName.isGetProp() && "exports".equals(exportsName.getFirstChild().getQualifiedName())) { String identifier = exportsName.getLastChild().getString(); String importName = fullname + "." + identifier; addExport(exportsName.getQualifiedName(), importName, identifier); if (importName != null && !namespaceToModule.containsKey(importName)) { namespaceToModule.put(importName, this); providesObjectChildren.put(importName, ImmutableSet.<String>of()); } } }

Target:
private void maybeAddGoogExport(Node exportsName) { String fullname = providesObjectChildren.keySet().iterator().next(); if ("exports".equals(exportsName.getQualifiedName())) { String identifier = firstNonNull( exportsName.getNext().getQualifiedName(), nameUtil.lastStepOfName(fullname)); addExport(exportsName.getQualifiedName(), fullname, identifier); } else if (exportsName.isGetProp() && "exports".equals(exportsName.getFirstChild().getQualifiedName())) { String identifier = exportsName.getLastChild().getString(); String importName = fullname + "." + identifier; addExport(exportsName.getQualifiedName(), importName, identifier); if (!namespaceToModule.containsKey(importName)) { namespaceToModule.put(importName, this); providesObjectChildren.put(importName, ImmutableSet.<String>of()); } } }
Source:
public Object handleResult(int status, Header[] headers, InputStream stream, HttpContext ctx) throws RemoteException, IOException { String ctype = getHeaderValue(headers, "Content-Type"); if (status >= Response.Status.BAD_REQUEST.getStatusCode()) { handleException(status, ctype, stream); } else if (status == Response.Status.NO_CONTENT.getStatusCode() || stream == null) { if (ctype != null && ctype.toLowerCase().startsWith(CTYPE_MULTIPART_EMPTY)) { return new Blobs(); } return null; } if (ctype == null) { if (status != Response.Status.OK.getStatusCode()) { throw new RemoteException(status, "ServerError", "Server Error", ""); } return null; } String disp = getHeaderValue(headers, "Content-Disposition"); String lctype = ctype.toLowerCase(); if (lctype.startsWith(CTYPE_AUTOMATION)) { return JsonMarshalling.readRegistry(IOUtils.read(stream)); } else if (lctype.startsWith(CTYPE_ENTITY)) { String body = IOUtils.read(stream); try { return JsonMarshalling.readEntity(body); } catch (IOException | RuntimeException e) { return readStringBlob(ctype, getFileName(disp), body); } } else if (lctype.startsWith(CTYPE_MULTIPART_MIXED)) { return readBlobs(ctype, stream); } else { return readBlob(ctype, getFileName(disp), stream); } }

Target:
public Object handleResult(int status, Header[] headers, InputStream stream, HttpContext ctx) throws RemoteException, IOException { String ctype = getHeaderValue(headers, HttpHeaders.CONTENT_TYPE); if (status >= Response.Status.BAD_REQUEST.getStatusCode()) { handleException(status, ctype, stream); } else if (status == Response.Status.NO_CONTENT.getStatusCode() || stream == null) { if (ctype != null && ctype.toLowerCase().startsWith(CTYPE_MULTIPART_EMPTY)) { return new Blobs(); } return null; } if (ctype == null) { if (status != Response.Status.OK.getStatusCode()) { throw new RemoteException(status, "ServerError", "Server Error", ""); } return null; } String disp = getHeaderValue(headers, HEADER_CONTENT_DISPOSITION); String lctype = ctype.toLowerCase(); if (lctype.startsWith(CTYPE_AUTOMATION)) { return JsonMarshalling.readRegistry(IOUtils.read(stream)); } else if (lctype.startsWith(CTYPE_ENTITY)) { String body = IOUtils.read(stream); try { return JsonMarshalling.readEntity(body); } catch (IOException | RuntimeException e) { return readStringBlob(ctype, getFileName(disp), body); } } else if (lctype.startsWith(CTYPE_MULTIPART_MIXED)) { return readBlobs(ctype, stream); } else { return readBlob(ctype, getFileName(disp), stream); } }
Source:
protected IResource getResource(IPath path) { if (path != null) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFileForLocation(path); if (file != null) { return file; } if (getType() != ARCHIVE) { IContainer container = root.getContainerForLocation(path); if (container != null) { return container; } } if (path.getDevice() == null) { return root.findMember(path); } } return null; }

Target:
protected IResource getResource(IPath path) { if (path != null) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); if (path.getDevice() == null) { IResource member = root.findMember(path); if (member != null) { return member; } } IFile file = root.getFileForLocation(path); if (file != null) { return file; } if (getType() != ARCHIVE) { IContainer container = root.getContainerForLocation(path); if (container != null) { return container; } } @SuppressWarnings("deprecation") IFile[] files = root.findFilesForLocation(path); if (files.length > 0) { return files[0]; } if (getType() != ARCHIVE) { @SuppressWarnings("deprecation") IContainer[] containers = root.findContainersForLocation(path); if (containers.length > 0) { return containers[0]; } } } return null; }
Source:
private Resource getMarkdownAsHtmlResource(String md, int lastModified, ResourceKey cacheKey) throws IOException { Map<String, String> macros = Maps.newHashMap(); macros.put("SSH_HOST", sshHost); macros.put("SSH_PORT", "" + sshPort); String url = webUrl.get(); if (Strings.isNullOrEmpty(url)) { url = "<LINK_0>"; } macros.put("URL", url); Matcher m = Pattern.compile("(\\\\)?@([A-Z_]+)@").matcher(md); StringBuffer sb = new StringBuffer(); while (m.find()) { String key = m.group(2); String val = macros.get(key); if (m.group(1) != null) { m.appendReplacement(sb, "@" + key + "@"); } else if (val != null) { m.appendReplacement(sb, val); } else { m.appendReplacement(sb, "@" + key + "@"); } } m.appendTail(sb); byte[] html = new MarkdownFormatter() .markdownToDocHtml(sb.toString(), "UTF-8", true); return new SmallResource(html) .setContentType("text/html") .setCharacterEncoding("UTF-8") .setLastModified(lastModified); }

Target:
private Resource getMarkdownAsHtmlResource(String md, int lastModified, ResourceKey cacheKey) throws IOException { Map<String, String> macros = Maps.newHashMap(); macros.put("SSH_HOST", sshHost); macros.put("SSH_PORT", "" + sshPort); String url = webUrl.get(); if (Strings.isNullOrEmpty(url)) { url = "<LINK_0>"; } macros.put("URL", url); Matcher m = Pattern.compile("(\\\\)?@([A-Z_]+)@").matcher(md); StringBuffer sb = new StringBuffer(); while (m.find()) { String key = m.group(2); String val = macros.get(key); if (m.group(1) != null || val == null) { m.appendReplacement(sb, "@" + key + "@"); } else { m.appendReplacement(sb, val); } } m.appendTail(sb); byte[] html = new MarkdownFormatter() .markdownToDocHtml(sb.toString(), "UTF-8", true); return new SmallResource(html) .setContentType("text/html") .setCharacterEncoding("UTF-8") .setLastModified(lastModified); }
Source:
public void onResume() { super.onResume(); if (player != null) { player.resume(); } if (null != playerController) { playerController.onResume(getActivity(), this); } }

Target:
public void onResume() { super.onResume(); if (player != null) { player.resume(); } if (playerController != null) { playerController.onResume(getActivity(), this); } }
Source:
public void beforeEach() { goGoDuckConfig = mock(GoGoDuckConfig.class); ggdm = new GoGoDuckModule("", new HttpIndexReader(null, ""), "TIME,1,2;LONGITUDE,2,3", null, goGoDuckConfig); }

Target:
public void beforeEach() { goGoDuckConfig = mock(GoGoDuckConfig.class); ggdm = new GoGoDuckModule("", null, "TIME,1,2;LONGITUDE,2,3", goGoDuckConfig); }
Source:
public void run() { try { IHandlerService handlerService = (IHandlerService) page.getActivePart().getSite().getService(IHandlerService.class); boolean executeCommand = (element instanceof TmfTraceElement); if (!executeCommand && element instanceof TmfExperimentElement) { TmfExperimentElement experiment = (TmfExperimentElement) element; executeCommand = (experiment.getTraces().size() > 0); } if (executeCommand) { handlerService.executeCommand(OPEN_COMMAND_ID, null); } } catch (ExecutionException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotDefinedException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotEnabledException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotHandledException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } }

Target:
public void run() { try { IHandlerService handlerService = (IHandlerService) page.getActivePart().getSite().getService(IHandlerService.class); boolean executeCommand = ((element instanceof TmfTraceElement) || (element instanceof TmfAnalysisOutputElement)); if (!executeCommand && element instanceof TmfExperimentElement) { TmfExperimentElement experiment = (TmfExperimentElement) element; executeCommand = (experiment.getTraces().size() > 0); } if (executeCommand) { handlerService.executeCommand(OPEN_COMMAND_ID, null); } } catch (ExecutionException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotDefinedException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotEnabledException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } catch (NotHandledException e) { Activator.getDefault().logError("Error opening resource " + element.getName(), e); } }
Source:
public static @Nullable Map<String, String> mapFromNmTextFile(File mappingFile) { Map<String, String> map = new HashMap<String, String>(); FileInputStream fis; try { fis = new FileInputStream(mappingFile); } catch (FileNotFoundException e) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] elems = line.split(" "); if (elems.length == 3) { String address = elems[0].replaceFirst("^0+(?!$)", ""); String name = elems[elems.length - 1]; map.put(address, name); } } reader.close(); } catch (IOException e) { try { reader.close(); } catch (IOException e1) } if (map.size() == 0) { return null; } return Collections.unmodifiableMap(map); }

Target:
public static @Nullable Map<String, String> mapFromNmTextFile(File mappingFile) { Map<String, String> map = new HashMap<String, String>(); FileReader fr; try { fr = new FileReader(mappingFile); } catch (FileNotFoundException e) { return null; } BufferedReader reader = new BufferedReader(fr); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] elems = line.split(" "); if (elems.length == 3) { String address = elems[0].replaceFirst("^0+(?!$)", ""); String name = elems[elems.length - 1]; map.put(address, name); } } } catch (IOException e) { } finally { try { reader.close(); } catch (IOException e) } if (map.isEmpty()) { return null; } return Collections.unmodifiableMap(map); }
Source:
private boolean filterInvalid(Position position) { return filterInvalid && !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180; }

Target:
private boolean filterInvalid(Position position) { if (filterInvalid == true) { return !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; } return false; }
Source:
private GcsStorageService googleCloudStorageService(String dataFilename) { GcsStorageService service; if (dataFilename == null) { service = new GcsStorageService(bucket, rootFolder, project, jsonPath, applicationVersion); } else { service = new GcsStorageService(bucket, rootFolder, project, jsonPath, applicationVersion, dataFilename); } service.ensureBucketExists(); log.info("Using Google Cloud Storage bucket={} in project={}", bucket, project); log.info("Bucket versioning is {}.", service.supportsVersioning() ? "enabled" : "DISABLED"); return service; }

Target:
private GcsStorageService googleCloudStorageService(String dataFilename) { GcsStorageService service; if (dataFilename == null || dataFilename.isEmpty()) { service = new GcsStorageService(bucket, rootFolder, project, jsonPath, applicationVersion); } else { service = new GcsStorageService(bucket, rootFolder, project, jsonPath, applicationVersion, dataFilename); } service.ensureBucketExists(); log.info("Using Google Cloud Storage bucket={} in project={}", bucket, project); log.info("Bucket versioning is {}.", service.supportsVersioning() ? "enabled" : "DISABLED"); return service; }