auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); SubscriptionItem subscriptionItem = SubscriptionItem.create(params); assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }

Target:
public void testCreate() throws StripeException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("plan", "plan_123"); params.put("subscription", "cus_123"); params.put("quantity", 99); final SubscriptionItem subscriptionItem = SubscriptionItem.create(params); assertNotNull(subscriptionItem); verifyRequest( APIResource.RequestMethod.POST, "/v1/subscription_items", params ); }
Source:
public static ComputerSystem logicalRouter2ComputerSystem(String logicalRouterName, InterfacesNamesList interfacesNames) { ComputerSystem logicalRouter = new ComputerSystem(); logicalRouter.setName(logicalRouterName); if (interfacesNames != null) { for (String interfaceName : interfacesNames.getInterfaces()) { logicalRouter.addLogicalDevice(subInterfaceName2NetworkPort(interfaceName)); } } return logicalRouter; }

Target:
public static ComputerSystem logicalRouter2ComputerSystem(String logicalRouterName, InterfacesNamesList interfacesNames) { ComputerSystem logicalRouter = new ComputerSystem(); logicalRouter.setName(logicalRouterName); logicalRouter.setElementName(logicalRouterName); if (interfacesNames != null) { for (String interfaceName : interfacesNames.getInterfaces()) { logicalRouter.addLogicalDevice(subInterfaceName2NetworkPort(interfaceName)); } } return logicalRouter; }
Source:
public void close() { if (mCompressedInputStream != null) { try { mCompressedInputStream.close(); } catch (IOException e) { throw new SAMException("Exception closing compressed input stream.", e); } } if (mStream != null) { mStream.close(); } if (mIndex != null) { mIndex.close(); } mStream = null; mFileHeader = null; mIndex = null; }

Target:
public void close() { if (mCompressedInputStream != null) { try { mCompressedInputStream.close(); } catch (IOException e) { throw new RuntimeIOException("Exception closing compressed input stream.", e); } } if (mStream != null) { mStream.close(); } if (mIndex != null) { mIndex.close(); } mStream = null; mFileHeader = null; mIndex = null; }
Source:
void scheduleNext() { synchronized (this) { if (pendingTasks.size() <= 0) { return; } do { pendingTasks.remove(); final InstrumentedTask task = pendingTasks.peek(); if (task == null) { return; } executeTask(task); } while (spaceAvailable()); } }

Target:
void scheduleNext() { synchronized (this) { if (pendingTasks.size() <= 0) { return; } pendingTasks.remove(); try { while (true) { final InstrumentedTask task = pendingTasks.peek(); if (task == null) { return; } if (!spaceAvailable()) { break; } task.setCompletion(this::finishTask); executeTask(task); pendingTasks.remove(); } } catch (RejectedExecutionException ignore) { } restartQueue(); } }
Source:
public DynamicBucketNodeMap(ToIntFunction<Split> splitToBucket, int bucketCount) { super(splitToBucket); this.bucketCount = bucketCount; }

Target:
public DynamicBucketNodeMap(ToIntFunction<Split> splitToBucket, int bucketCount) { super(splitToBucket); checkArgument(bucketCount > 0, "bucketCount must be positive"); this.bucketCount = bucketCount; }
Source:
public void testListWithOptions() throws Exception { String lexicographicallyBeforeName = name.substring(0, name.length() - 1); for (String regionId : regions) { ListContainerOptions options = ListContainerOptions.Builder.marker(lexicographicallyBeforeName); Container container = api.getContainerApi(regionId).list(options).firstMatch(new Predicate<Container>() { @Override public boolean apply(Container container) { return container.getName().equals(name); } }).get(); assertNotNull(container); assertEquals(container.getName(), name); assertTrue(container.getObjectCount() == 0); assertTrue(container.getBytesUsed() == 0); } }

Target:
public void testListWithOptions() throws Exception { String lexicographicallyBeforeName = name.substring(0, name.length() - 1); for (String regionId : regions) { ListContainerOptions options = ListContainerOptions.Builder.marker(lexicographicallyBeforeName); Container container = api.getContainerApi(regionId).list(options).firstMatch(new Predicate<Container>() { @Override public boolean apply(Container container) { return container.getName().equals(name); } }).get(); assertTrue(container.getObjectCount() == 0); assertTrue(container.getBytesUsed() == 0); } }
Source:
private void init() { try{ migrateDatasets(); migratePerspectives(); migrateNavigation(); } catch (Exception e) { LOGGER.error("Failed during dashbuilder migration process."); } }

Target:
private void init() { try{ if (!clusterParameters.isAppFormerClustered()) { migrateDatasets(); migratePerspectives(); migrateNavigation(); } } catch (Exception e) { LOGGER.error("Failed during dashbuilder migration process."); LOGGER.debug("Error during dashbuilder migration", e); } }
Source:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); client.updateMetadata(initialUpdateResponseWithLeaderEpoch); Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }

Target:
public void testFetchSkipsBlackedOutNodes() { buildFetcher(); assignFromUser(singleton(tp0)); subscriptions.seek(tp0, 0); Node node = initialUpdateResponse.brokers().iterator().next(); client.blackout(node, 500); assertEquals(0, fetcher.sendFetches()); time.sleep(500); assertEquals(1, fetcher.sendFetches()); }
Source:
private void analyzeReplLoad(ASTNode ast) throws SemanticException { try { initReplLoad(ast); } catch (HiveException e) { throw new SemanticException(e); } try { assert(sourceDbNameOrPattern != null); Path loadPath = getCurrentLoadPath(); try { Warehouse wh = new Warehouse(conf); Path filePath = wh.getWhRoot(); if (ifEnableMoveOptimization(filePath, conf)) { conf.setBoolVar(REPL_ENABLE_MOVE_OPTIMIZATION, true); LOG.info(" Set move optimization to true for warehouse " + filePath.toString()); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } if (isTargetAlreadyLoaded) { return; } else { DumpMetaData dmd = new DumpMetaData(loadPath, conf); boolean evDump = false; if (dmd.isIncrementalDump()) { LOG.debug("{} contains an incremental dump", loadPath); evDump = true; } else { LOG.debug("{} contains an bootstrap dump", loadPath); } ReplLoadWork replLoadWork = new ReplLoadWork(conf, loadPath.toString(), replScope.getDbName(), dmd.getReplScope(), queryState.getLineageState(), evDump, dmd.getEventTo(), dirLocationsToCopy(loadPath, evDump)); rootTasks.add(TaskFactory.get(replLoadWork, conf)); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }

Target:
private void analyzeReplLoad(ASTNode ast) throws SemanticException { try { initReplLoad(ast); } catch (HiveException e) { throw new SemanticException(e); } try { assert(sourceDbNameOrPattern != null); Path loadPath = getCurrentLoadPath(); try { Warehouse wh = new Warehouse(conf); Path filePath = wh.getWhRoot(); if (ifEnableMoveOptimization(filePath, conf)) { conf.setBoolVar(REPL_ENABLE_MOVE_OPTIMIZATION, true); LOG.info(" Set move optimization to true for warehouse " + filePath.toString()); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } if (!isTargetAlreadyLoaded) { DumpMetaData dmd = new DumpMetaData(loadPath, conf); boolean evDump = false; if (dmd.isIncrementalDump()) { LOG.debug("{} contains an incremental dump", loadPath); evDump = true; } else { LOG.debug("{} contains an bootstrap dump", loadPath); } ReplLoadWork replLoadWork = new ReplLoadWork(conf, loadPath.toString(), replScope.getDbName(), dmd.getReplScope(), queryState.getLineageState(), evDump, dmd.getEventTo(), dirLocationsToCopy(loadPath, evDump)); rootTasks.add(TaskFactory.get(replLoadWork, conf)); } } catch (Exception e) { throw new SemanticException(e.getMessage(), e); } }
Source:
public void testVcf42Roundtrip() throws Exception { File expectedFile = new File("src/test/resources/htsjdk/variant/Vcf4.2WithSourceVersionInfoFields.vcf"); final VCFFileReader originalFileReader = new VCFFileReader(expectedFile, false); final VCFHeader originalHeader = originalFileReader.getFileHeader(); final File actualFile = File.createTempFile("testVcf4.2roundtrip.", IOUtil.VCF_FILE_EXTENSION); actualFile.deleteOnExit(); final VariantContextWriter copyWriter = new VariantContextWriterBuilder() .setOutputFile(actualFile) .setReferenceDictionary(createArtificialSequenceDictionary()) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY)) .build(); copyWriter.writeHeader(originalHeader); final CloseableIterator<VariantContext> firstCopyVariantIterator = originalFileReader.iterator(); while (firstCopyVariantIterator.hasNext()) { VariantContext variantContext = firstCopyVariantIterator.next(); copyWriter.add(variantContext); } originalFileReader.close(); copyWriter.close(); final String actualContents = new String(Files.readAllBytes(actualFile.toPath()), StandardCharsets.UTF_8); final String expectedContents = new String(Files.readAllBytes(expectedFile.toPath()), StandardCharsets.UTF_8); Assert.assertEquals(actualContents, expectedContents); }

Target:
public void testVcf42Roundtrip() throws Exception { File expectedFile = new File("src/test/resources/htsjdk/variant/Vcf4.2WithSourceVersionInfoFields.vcf"); final File actualFile = File.createTempFile("testVcf4.2roundtrip.", IOUtil.VCF_FILE_EXTENSION); actualFile.deleteOnExit(); try (final VCFFileReader originalFileReader = new VCFFileReader(expectedFile, false); final VariantContextWriter copyWriter = new VariantContextWriterBuilder() .setOutputFile(actualFile) .setReferenceDictionary(createArtificialSequenceDictionary()) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY)) .build() ) { final VCFHeader originalHeader = originalFileReader.getFileHeader(); copyWriter.writeHeader(originalHeader); for (final VariantContext variantContext : originalFileReader) { copyWriter.add(variantContext); } } final String actualContents = new String(Files.readAllBytes(actualFile.toPath()), StandardCharsets.UTF_8); final String expectedContents = new String(Files.readAllBytes(expectedFile.toPath()), StandardCharsets.UTF_8); Assert.assertEquals(actualContents, expectedContents); }
Source:
public boolean add(E e) { if (this.underlyingQueue.add(new ThroughputElement<E>(e))) { this.elementsAdded.incrementAndGet(); synchronized (this) { if (!this.active) { this.startTime.set(System.currentTimeMillis()); this.active = true; } } return true; } return false; }

Target:
public boolean add(E e) { if (this.underlyingQueue.add(new ThroughputElement<E>(e))) { internalAddElement(); return true; } return false; }
Source:
public void shouldConstructANewEntity() { ChargeEntity chargeEntity = aValidChargeEntity().build(); Long amount = 100L; RefundEntity refundEntity = new RefundEntity(chargeEntity, amount, null); assertNotNull(refundEntity.getExternalId()); assertThat(refundEntity.getChargeEntity(), is(chargeEntity)); assertThat(refundEntity.getReference(), is(nullValue())); assertThat(refundEntity.getAmount(), is(amount)); assertThat(refundEntity.getStatus(), is(RefundStatus.CREATED)); assertNotNull(refundEntity.getCreatedDate()); }

Target:
public void shouldConstructANewEntity() { ChargeEntity chargeEntity = aValidChargeEntity().build(); Long amount = 100L; RefundEntity refundEntity = new RefundEntity(chargeEntity, amount, userExternalId); assertNotNull(refundEntity.getExternalId()); assertThat(refundEntity.getChargeEntity(), is(chargeEntity)); assertThat(refundEntity.getReference(), is(nullValue())); assertThat(refundEntity.getAmount(), is(amount)); assertThat(refundEntity.getStatus(), is(RefundStatus.CREATED)); assertThat(refundEntity.getUserExternalId(), is(userExternalId)); assertNotNull(refundEntity.getCreatedDate()); }
Source:
private void schedule() { int delay = initialDelay * (int) Math.pow(delayGrowth, failedAttempts); if (maxDelay != -1 && delay > maxDelay) { log.debug("Maximum delay reached", maxDelay); delay = maxDelay; } log.debug("Next Transitioner check will run after seconds", delay); if (failedAttempts > 3) { log.info("SuspendModeTransitioner failed to reconnect to the Qpid Broker " + "{} times, backing off with next reconnect seconds", failedAttempts, delay); } execService.schedule(this, delay, TimeUnit.SECONDS); }

Target:
private void schedule() { BigInteger delay = BigInteger.valueOf(initialDelay) .add(BigInteger.valueOf(delayGrowth) .multiply(failedAttempts)); if (maxDelay != -1 && delay.compareTo(BigInteger.valueOf(maxDelay)) > 0) { log.debug("Maximum delay reached", maxDelay); delay = BigInteger.valueOf(maxDelay); } log.debug("Next Transitioner check will run after seconds", delay); if (failedAttempts.compareTo(BigInteger.ZERO) > 0) { log.info("SuspendModeTransitioner failed to reconnect to the Qpid Broker " + "{} times, backing off with next reconnect seconds", failedAttempts, delay); } execService.schedule(this, delay.longValue(), TimeUnit.SECONDS); }
Source:
public static MultiFactorAuthenticationSupportingWebApplicationService createServiceFrom(final HttpServletRequest request, final HttpClient httpClient, final List<String> supportedLevelsOfAuthentication) { LOGGER.debug("Attempting to extract multifactor authentication parameters from the request"); final String targetService = request.getParameter(CONST_PARAM_TARGET_SERVICE); final String loa = request.getParameter(CONST_PARAM_AUTHN_METHOD); final String serviceToUse = StringUtils.hasText(targetService) ? targetService : request.getParameter(CONST_PARAM_SERVICE); if (!StringUtils.hasText(serviceToUse)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_SERVICE); return null; } if (!StringUtils.hasText(loa)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_AUTHN_METHOD); return null; } if (!supportedLevelsOfAuthentication.contains(loa)) { LOGGER.debug("Multifactor authentication service does not support parameter value [{}].", CONST_PARAM_AUTHN_METHOD, loa); return null; } final String id = cleanupUrl(serviceToUse); final String artifactId = request.getParameter(CONST_PARAM_TICKET); final MultiFactorAuthenticationSupportingWebApplicationService svc = new DefaultMultiFactorAuthenticationSupportingWebApplicationService( id, serviceToUse, artifactId, httpClient, loa); LOGGER.debug("Created multifactor authentication request for with as [{}].", svc.getId(), CONST_PARAM_AUTHN_METHOD, svc.getAuthenticationMethod()); return svc; }

Target:
public static MultiFactorAuthenticationSupportingWebApplicationService createServiceFrom(final HttpServletRequest request, final HttpClient httpClient, final List<String> supportedLevelsOfAuthentication) { LOGGER.debug("Attempting to extract multifactor authentication parameters from the request"); final String targetService = request.getParameter(CONST_PARAM_TARGET_SERVICE); final String authenticationMethod = request.getParameter(CONST_PARAM_AUTHN_METHOD); final String serviceToUse = StringUtils.hasText(targetService) ? targetService : request.getParameter(CONST_PARAM_SERVICE); if (!StringUtils.hasText(serviceToUse)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_SERVICE); return null; } if (!StringUtils.hasText(authenticationMethod)) { LOGGER.debug("Request has no request parameter [{}]", CONST_PARAM_AUTHN_METHOD); return null; } if (!supportedLevelsOfAuthentication.contains(authenticationMethod)) { LOGGER.debug("Multifactor authentication service does not support parameter value [{}].", CONST_PARAM_AUTHN_METHOD, authenticationMethod); return null; } final String id = cleanupUrl(serviceToUse); final String artifactId = request.getParameter(CONST_PARAM_TICKET); final MultiFactorAuthenticationSupportingWebApplicationService svc = new DefaultMultiFactorAuthenticationSupportingWebApplicationService( id, serviceToUse, artifactId, httpClient, authenticationMethod); LOGGER.debug("Created multifactor authentication request for with as [{}].", svc.getId(), CONST_PARAM_AUTHN_METHOD, svc.getAuthenticationMethod()); return svc; }
Source:
public static String getKeyBytesSha(byte[] keyBytes) { String keyBytesSha; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] sha = digest.digest(keyBytes); keyBytesSha = Base64.encodeBytes(sha); } catch(NoSuchAlgorithmException e) { throw new JpaStoreException("Failed to create SHA hash of metadata key", e); } return keyBytesSha; }

Target:
public static String getKeyBytesSha(byte[] keyBytes) { String keyBytesSha; try { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALG); byte[] sha = digest.digest(keyBytes); keyBytesSha = Base64.encodeBytes(sha); } catch(NoSuchAlgorithmException e) { throw new JpaStoreException("Failed to create SHA hash of metadata key", e); } return keyBytesSha; }
Source:
static boolean canHandle(final URIish uri, FS fs) throws NotSupportedException { if (uri.getHost() != null || uri.getPort() > 0 || uri.getUser() != null || uri.getPass() != null || uri.getPath() == null) return false; if ("file".equals(uri.getScheme()) || uri.getScheme() == null) { if (fs.resolve(new File(PWD), uri.getPath()).isDirectory()) { return true; } else { throw new NotSupportedException(uri.getPath() + " does not exist"); } } return false; }

Target:
static boolean canHandle(final URIish uri, FS fs) throws NotSupportedException { if (uri.getHost() != null || uri.getPort() > 0 || uri.getUser() != null || uri.getPass() != null || uri.getPath() == null) return false; if ("file".equals(uri.getScheme()) || uri.getScheme() == null) { if (fs.resolve(new File(PWD), uri.getPath()).isDirectory()) { return true; } else { throw new NotSupportedException(MessageFormat.format( JGitText.get().cannotFindRepository, uri.getPath())); } } return false; }
Source:
protected int run() throws Exception { Jenkins.getActiveInstance().checkPermission(Jenkins.ADMINISTER); Binding binding = new Binding(); binding.setProperty("out",new PrintWriter(stdout,true)); binding.setProperty("stdin",stdin); binding.setProperty("stdout",stdout); binding.setProperty("stderr",stderr); GroovyShell groovy = new GroovyShell(Jenkins.get().getPluginManager().uberClassLoader, binding); groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); return 0; }

Target:
protected int run() throws Exception { Jenkins.get().checkPermission(Jenkins.ADMINISTER); Binding binding = new Binding(); binding.setProperty("out",new PrintWriter(stdout,true)); binding.setProperty("stdin",stdin); binding.setProperty("stdout",stdout); binding.setProperty("stderr",stderr); GroovyShell groovy = new GroovyShell(Jenkins.get().getPluginManager().uberClassLoader, binding); groovy.run(loadScript(),"RemoteClass",remaining.toArray(new String[0])); return 0; }
Source:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { getTempFile().delete(); tmpFile.close(); tmpFile = null; txFile = null; } freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }

Target:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { tmpFile.close(); getTempFile().delete(); tmpFile = null; txFile = null; } freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }
Source:
public void addEntries(ISourceContainer[] entries) { int index = 0; IStructuredSelection sel = getStructuredSelection(); if (!sel.isEmpty()) { index = fEntries.indexOf(sel.getFirstElement()); } for (ISourceContainer entrie : entries) { if (!fEntries.contains(entrie)) { fEntries.add(index, entrie); index++; } } refresh(); if(entries.length > 0) { setSelection(new StructuredSelection(entries)); } fPanel.setDirty(true); fPanel.updateLaunchConfigurationDialog(); }

Target:
public void addEntries(ISourceContainer[] entries) { int index = 0; IStructuredSelection sel = getStructuredSelection(); if (!sel.isEmpty()) { index = fEntries.indexOf(sel.getFirstElement()); } for (ISourceContainer entry : entries) { if (!fEntries.contains(entry)) { fEntries.add(index, entry); index++; } } refresh(); if(entries.length > 0) { setSelection(new StructuredSelection(entries)); } fPanel.setDirty(true); fPanel.updateLaunchConfigurationDialog(); }
Source:
private void setConflictsWith(GerritClient gerritClient, ChangeInfo element) { ChangeInfo[] conflictsWithChangeInfo = null; if (!("MERGED".equals(element.getStatus())) && !("ABANDONED".equals(element.getStatus()))) { try { conflictsWithChangeInfo = queryConflictsWith(gerritClient, element.getChange_id(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(gerritClient.getRepository().formatGerritVersion() + e.getMessage()); } List<ChangeInfo> conflictsWithChangeInfolistNew = new ArrayList<ChangeInfo>(); if (conflictsWithChangeInfo != null) { for (ChangeInfo element2 : conflictsWithChangeInfo) { if (element2.getChange_id().compareTo(fChangeInfo.getChange_id()) != 0) { conflictsWithChangeInfolistNew.add(element2); } } } fChangeInfo.getConflictsWith().clear(); fChangeInfo.getConflictsWith().addAll(conflictsWithChangeInfolistNew); } }

Target:
private void setConflictsWith(GerritClient gerritClient, ChangeInfo element) { ChangeInfo[] conflictsWithChangeInfo = null; if (!("MERGED".equals(element.getStatus())) && !("ABANDONED".equals(element.getStatus()))) { try { conflictsWithChangeInfo = queryConflictsWith(gerritClient, element.getChange_id(), new NullProgressMonitor()); } catch (MalformedURLException e) { EGerritCorePlugin.logError(gerritClient.getRepository().formatGerritVersion() + e.getMessage()); } List<ChangeInfo> conflictsWithChangeInfolistNew = new ArrayList<ChangeInfo>(); if (conflictsWithChangeInfo != null) { for (ChangeInfo conflictChangeInfo : conflictsWithChangeInfo) { if (conflictChangeInfo.getChange_id().compareTo(fChangeInfo.getChange_id()) != 0) { conflictsWithChangeInfolistNew.add(conflictChangeInfo); } } } fChangeInfo.getConflictsWith().clear(); fChangeInfo.getConflictsWith().addAll(conflictsWithChangeInfolistNew); } }
Source:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } List<CompletableFuture> futures = new ArrayList<>(MAX_ASYNC_EXPIRATIONS); long currentTimeMillis = timeService.wallClockTime(); dataContainer.forEachExpired((ice, segment) -> { if (ice.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (ice) { value = ice.getValue(); lifespan = ice.getLifespan(); maxIdle = ice.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis); } if (expiredMortal) { addAndWaitIfFull(handleLifespanExpireEntry(ice.getKey(), value, lifespan), futures); } else if (expiredTransient) { addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(ice.getKey(), value, maxIdle), futures); } } }); if (!futures.isEmpty()) { futures.forEach(CompletableFuture::join); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }

Target:
public void processExpiration() { long start = 0; if (!Thread.currentThread().isInterrupted()) { try { if (trace) { log.trace("Purging data container of expired entries"); start = timeService.time(); } List<CompletableFuture> futures = new ArrayList<>(MAX_ASYNC_EXPIRATIONS); long currentTimeMillis = timeService.wallClockTime(); dataContainer.forEachIncludingExpired((ice, segment) -> { if (ice.canExpire()) { boolean expiredMortal; boolean expiredTransient; V value; long lifespan; long maxIdle; synchronized (ice) { value = ice.getValue(); lifespan = ice.getLifespan(); maxIdle = ice.getMaxIdle(); expiredMortal = ExpiryHelper.isExpiredMortal(lifespan, ice.getCreated(), currentTimeMillis); expiredTransient = ExpiryHelper.isExpiredTransient(maxIdle, ice.getLastUsed(), currentTimeMillis); } if (expiredMortal) { addAndWaitIfFull(handleLifespanExpireEntry(ice.getKey(), value, lifespan), futures); } else if (expiredTransient) { addAndWaitIfFull(actualRemoveMaxIdleExpireEntry(ice.getKey(), value, maxIdle), futures); } } }); if (!futures.isEmpty()) { futures.forEach(CompletableFuture::join); } if (trace) { log.tracef("Purging data container completed in %s", Util.prettyPrintTime(timeService.timeDuration(start, TimeUnit.MILLISECONDS))); } } catch (Exception e) { log.exceptionPurgingDataContainer(e); } } if (!Thread.currentThread().isInterrupted()) { persistenceManager.purgeExpired(); } }
Source:
public int read() throws IOException { return input.read(); }

Target:
public int read() throws IOException { return zipInput.read(); }
Source:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String additionalPath = request.getPathInfo(); if (additionalPath.equals(CREATE_URL) || additionalPath.equals(INFO_URL)) { String configProp = request.getParameter("config"); Properties initParameters = this.initParametersOrig; if (configProp != null) { LOG.info("Set config to '" + configProp + "'"); } else { LOG.info("Use original config '" + this.configPropOrig + "'"); configProp = this.configPropOrig; } initParameters = setConfig(initParameters, configProp); super.setInitParameters(initParameters); super.afterPropertiesSet(); } return super.handleRequestInternal(request, response); }

Target:
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { final String additionalPath = request.getPathInfo(); synchronized (additionalPath) { if (additionalPath.equals(CREATE_URL) || additionalPath.equals(INFO_URL)) { String configProp = request.getParameter("config"); Properties initParameters = this.initParametersOrig; if (configProp != null) { LOG.info("Set config to '" + configProp + "'"); } else { LOG.info("Use original config '" + this.configPropOrig + "'"); configProp = this.configPropOrig; } initParameters = setConfig(initParameters, configProp); super.setInitParameters(initParameters); super.afterPropertiesSet(); } return super.handleRequestInternal(request, response); } }
Source:
private void invalidate(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); clientsToInvalidate.remove(originatingClientDescriptor); InvalidationHolder invalidationHolder = null; if (stores.get(cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); } LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client {}" + clientDescriptorThatHasToInvalidate + " to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }

Target:
private void invalidate(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); clientsToInvalidate.remove(originatingClientDescriptor); InvalidationHolder invalidationHolder = null; if (stores.get(cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); } LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }
Source:
public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { boolean shiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); if( shiftHeld ) { ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); ItemStack output = iep.getOutput( stack ); if( output != null && !output.isEmpty() ) { IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel( output ); realModel = realModel.getOverrides().handleItemState( realModel, output, world, entity ); return new ShiftHoldingModelWrapper( realModel ); } } return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState( originalModel, stack, world, entity ); }

Target:
public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { boolean shiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); if( shiftHeld ) { ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); ItemStack output = iep.getOutput( stack ); if( !output.isEmpty() ) { IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel( output ); realModel = realModel.getOverrides().handleItemState( realModel, output, world, entity ); return new ShiftHoldingModelWrapper( realModel ); } } return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState( originalModel, stack, world, entity ); }
Source:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getCredentialsNew().equals(userCredentials.getConfirmedCredentialsNew())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (AuthenticationException ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); log.debug(msg, ex); SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getNewCredentials().equals(userCredentials.getConfirmedNewCredentials())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (AuthenticationException ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); log.debug(msg, ex); SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }
Source:
private static Properties loadBuildProperties() { Properties prop = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { prop.load(loader.getResourceAsStream("git.properties")); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }

Target:
private static Properties loadBuildProperties() { Properties prop = new Properties(); try { prop.load(Update.class.getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }
Source:
public DataCenterListResponseHandler(DateCodecFactory dateCodec) { super(dateCodec); this.dataCenters = Lists.newArrayList(); }

Target:
DataCenterListResponseHandler(DateCodecFactory dateCodec) { super(dateCodec); this.dataCenters = Lists.newArrayList(); }
Source:
public static RadioPlayerFeedCompiler valueOf(FileType type) { checkState(compilerMap != null, "Compiler map not initialised"); return checkNotNull(compilerMap.get(type), "No compiler for type " + type); }

Target:
public static RadioPlayerFeedCompiler valueOf(FileType type) { checkState(compilerMap != null, "Compiler map not initialised"); RadioPlayerFeedCompiler compiler = compilerMap.get(type); checkArgument(compiler != null, "No compiler for type " + type); return compiler; }
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<>(); if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }
Source:
public void testTimestamp() throws InvalidParametersException, EntityAlreadyExistsException, EntityDoesNotExistException { ______TS("success : created"); FeedbackQuestionAttributes fq = getNewFeedbackQuestionAttributes(); fqDb.createEntity(fq); verifyPresentInDatastore(fq, true); String feedbackSessionName = fq.feedbackSessionName; String courseId = fq.courseId; int questionNumber = fq.questionNumber; FeedbackQuestionAttributes feedbackQuestion = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, questionNumber); AssertHelper.assertDateIsNow(feedbackQuestion.getCreatedAt()); AssertHelper.assertDateIsNow(feedbackQuestion.getUpdatedAt()); ______TS("success : update lastUpdated"); int newQuestionNumber = questionNumber + 1; feedbackQuestion.questionNumber = newQuestionNumber; fqDb.updateFeedbackQuestion(feedbackQuestion); FeedbackQuestionAttributes updatedFq = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, newQuestionNumber); assertFalse(feedbackQuestion.getUpdatedAt().equals(updatedFq.getUpdatedAt())); AssertHelper.assertDateIsNow(updatedFq.getUpdatedAt()); ______TS("success : keep lastUpdated"); int newQuestionNumberTwo = newQuestionNumber + 1; feedbackQuestion.questionNumber = newQuestionNumberTwo; fqDb.updateFeedbackQuestion(feedbackQuestion, true); FeedbackQuestionAttributes updatedFq2 = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, newQuestionNumberTwo); assertTrue(updatedFq.getUpdatedAt().equals(updatedFq2.getUpdatedAt())); fqDb.deleteEntity(updatedFq2); }

Target:
public void testTimestamp() throws InvalidParametersException, EntityAlreadyExistsException, EntityDoesNotExistException { ______TS("success : created"); FeedbackQuestionAttributes fq = getNewFeedbackQuestionAttributes(); fqDb.createEntity(fq); verifyPresentInDatastore(fq, true); String feedbackSessionName = fq.feedbackSessionName; String courseId = fq.courseId; int questionNumber = fq.questionNumber; FeedbackQuestionAttributes feedbackQuestion = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, questionNumber); AssertHelper.assertDateIsNow(feedbackQuestion.getCreatedAt()); AssertHelper.assertDateIsNow(feedbackQuestion.getUpdatedAt()); ______TS("success : update lastUpdated"); feedbackQuestion.questionNumber++; fqDb.updateFeedbackQuestion(feedbackQuestion); FeedbackQuestionAttributes updatedFq = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, feedbackQuestion.questionNumber); assertFalse(feedbackQuestion.getUpdatedAt().equals(updatedFq.getUpdatedAt())); AssertHelper.assertDateIsNow(updatedFq.getUpdatedAt()); ______TS("success : keep lastUpdated"); feedbackQuestion.questionNumber++; fqDb.updateFeedbackQuestion(feedbackQuestion, true); FeedbackQuestionAttributes updatedFqTwo = fqDb.getFeedbackQuestion(feedbackSessionName, courseId, feedbackQuestion.questionNumber); assertEquals(updatedFq.getUpdatedAt(), updatedFqTwo.getUpdatedAt()); fqDb.deleteEntity(updatedFqTwo); }
Source:
private Integer getCounterValue(Request request) { try { int counter = Integer.parseInt(request.params("pipeline_counter"), 10); if (counter < 1) { throw new UnprocessableEntityException("The pipeline counter cannot be less than 1."); } return counter; } catch (NumberFormatException ex) { throw new UnprocessableEntityException("The pipeline counter should be an integer."); } }

Target:
private Integer getCounterValue(Request request) { try { int counter = Integer.parseInt(request.params("pipeline_counter")); if (counter < 1) { throw new UnprocessableEntityException("The pipeline counter cannot be less than 1."); } return counter; } catch (NumberFormatException ex) { throw new UnprocessableEntityException("The pipeline counter should be an integer."); } }
Source:
public void alterAddColumnToCloudUsage(final Connection conn) { final String alterTableSql = "ALTER TABLE `cloud_usage`.`cloud_usage` ADD COLUMN `quota_calculated` tinyint(1) DEFAULT 0 NOT NULL COMMENT 'quota calculation status'"; try (PreparedStatement pstmt = conn.prepareStatement(alterTableSql)) { pstmt.executeUpdate(); s_logger.info("Altered usage table and added column quota_calculated"); } catch (SQLException e) { if (e.getMessage().contains("quota_calculated")) { s_logger.warn("Usage table already has a column called quota_calculated"); } else { throw new CloudRuntimeException("Unable to create column quota_calculated", e); } } }

Target:
public void alterAddColumnToCloudUsage(final Connection conn) { final String alterTableSql = "ALTER TABLE `cloud_usage`.`cloud_usage` ADD COLUMN `quota_calculated` tinyint(1) DEFAULT 0 NOT NULL COMMENT 'quota calculation status'"; try (PreparedStatement pstmt = conn.prepareStatement(alterTableSql)) { pstmt.executeUpdate(); s_logger.info("Altered cloud_usage.cloud_usage table and added column quota_calculated"); } catch (SQLException e) { if (e.getMessage().contains("quota_calculated")) { s_logger.warn("cloud_usage.cloud_usage table already has a column called quota_calculated"); } else { throw new CloudRuntimeException("Unable to create column quota_calculated in table cloud_usage.cloud_usage", e); } } }
Source:
private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } } }); }

Target:
private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }
Source:
public List<Result> allResults() { randomAccess = true; return new ResultSetList(); }

Target:
public List<Result> allResults() { List<Result> results = new ArrayList<>(); Result result; while ((result = next()) != null) results.add(result); return results; }
Source:
public void setup(final String headerKey, final String labelKey) { getView().setHeader(translationService.format(headerKey)); getView().setLabel(translationService.format(labelKey)); superSetup(); }

Target:
public void setup(final String headerKey, final String labelKey) { getView().setHeader(translationService.format(headerKey)); getView().setLabel(translationService.format(labelKey)); setup(); }
Source:
public static BranchOptionsEnum fromInitValue(String initKey) { for (BranchOptionsEnum optEnum : values()) { if (optEnum.origKeyName.equals(initKey)) { return optEnum; } } throw new IllegalArgumentException(String.format("Incorrect BranchOptionEnum value")); }

Target:
public static BranchOptionsEnum fromInitValue(String initKey) { for (BranchOptionsEnum optEnum : values()) { if (optEnum.origKeyName.equals(initKey)) { return optEnum; } } throw new IllegalArgumentException(String.format("Incorrect BranchOptionEnum value: " + initKey)); }
Source:
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException { if (defaultJSch == null) { defaultJSch = createDefaultJSch(fs); for (final Object name : defaultJSch.getIdentityNames()) { byIdentityFile.put((String) name, defaultJSch); } } final File identityFile = hc.getIdentityFile(); if (identityFile == null) { return defaultJSch; } final String identityKey = identityFile.getAbsolutePath(); JSch jsch = byIdentityFile.get(identityKey); if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository()); jsch.addIdentity(identityKey); byIdentityFile.put(identityKey, jsch); } return jsch; }

Target:
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException { if (defaultJSch == null) { defaultJSch = createDefaultJSch(fs); for (Object name : defaultJSch.getIdentityNames()) byIdentityFile.put((String) name, defaultJSch); } final File identityFile = hc.getIdentityFile(); if (identityFile == null) return defaultJSch; final String identityKey = identityFile.getAbsolutePath(); JSch jsch = byIdentityFile.get(identityKey); if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository()); jsch.addIdentity(identityKey); byIdentityFile.put(identityKey, jsch); } return jsch; }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { List<ServiceName> failures = new ArrayList<>(); ServiceRegistry registry = context.getServiceRegistry(false); for (ServiceName serviceName : requiredServices) { try { ServiceController<?> controller = registry.getService(serviceName); if (controller == null || State.UP != controller.getState()) { failures.add(serviceName); } } catch (ServiceNotFoundException ex) { failures.add(serviceName); } } if (failures.containsAll(requiredServices)) { context.setRollbackOnly(); ModelNode requiredServicesNode = context.getFailureDescription().get(ROOT_LOGGER.missingRequiredServices()); for (ServiceName serviceName : failures) { requiredServicesNode.add(serviceName.getCanonicalName()); } } }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { Boolean attachment = context.getAttachment(MANAGEMENT_INTERFACE_KEY); if (attachment == null ||!context.getAttachment(MANAGEMENT_INTERFACE_KEY)) { context.setRollbackOnly(); } }
Source:
static private int requireNonNullInt(String required, String message) throws ConfigurationRuntimeException { if (required == null) throw new ConfigurationRuntimeException(message); try { return Integer.parseInt(required); } catch (NumberFormatException e) { throw new ConfigurationRuntimeException(message); } }

Target:
private static int requireNonNullInt(String required, String message) throws ConfigurationRuntimeException { if (required == null) throw new ConfigurationRuntimeException(message); try { return Integer.parseInt(required); } catch (NumberFormatException e) { throw new ConfigurationRuntimeException(message); } }
Source:
public Optional<String> getBrokerServiceName(TieredBrokerConfig tierConfig, Query query) { final int priority = QueryContexts.getPriority(query); if (priority < minPriority) { return Optional.of( tierConfig.getDefaultBrokerServiceName() ); } else if (priority >= maxPriority) { return Optional.of(tierConfig.getDefaultBrokerServiceName()); } return Optional.absent(); }

Target:
public Optional<String> getBrokerServiceName(TieredBrokerConfig tierConfig, Query query) { final int priority = QueryContexts.getPriority(query); if (priority < minPriority || priority > maxPriority) { return Optional.of( tierConfig.getDefaultBrokerServiceName() ); } return Optional.absent(); }
Source:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; for (int i = 0; i < 7; i++) { if (ti.getText(i).contains(text)) { return true; } } return false; }

Target:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; if (ti.getText().contains(text)) { return true; } return false; }
Source:
private static AddModuleWizard createImportWizard(@NotNull VirtualFile file) throws IOException, ConfigurationException { VirtualFile target = ProjectImportUtil.findImportTarget(file); if (target == null) { return null; } VirtualFile targetDir = target.isDirectory() ? target : target.getParent(); File targetDirFile = VfsUtilCore.virtualToIoFile(targetDir); if (ADTModuleImporter.isADTProjectLocation(file)) { importAdtProject(file); } else if (GradleImport.isEclipseProjectDir(targetDirFile) && targetDir.findChild(SdkConstants.FN_BUILD_GRADLE) == null && !ApplicationManager.getApplication().isUnitTestMode()) { String message = String.format("%1$s is in an Eclipse project, but not an Android Eclipse project.\n\n" + "Please select the directory of an Android Eclipse project" + "(which for example will contain\nan AndroidManifest.xml file) and try again.", file.getPath()); Messages.showErrorDialog(message, "Import Project"); } else if (GradleModuleImporter.isGradleProject(target)) { GradleProjectImporter gradleImporter = GradleProjectImporter.getInstance(); gradleImporter.importProject(file); } else { return importWithExtensions(file); } return null; }

Target:
private static AddModuleWizard createImportWizard(@NotNull VirtualFile file) throws IOException, ConfigurationException { VirtualFile target = ProjectImportUtil.findImportTarget(file); if (target == null) { return null; } VirtualFile targetDir = target.isDirectory() ? target : target.getParent(); File targetDirFile = VfsUtilCore.virtualToIoFile(targetDir); if (AdtModuleImporter.isAdtProjectLocation(file)) { importAdtProject(file); } else if (GradleImport.isEclipseProjectDir(targetDirFile) && targetDir.findChild(SdkConstants.FN_BUILD_GRADLE) == null && !ApplicationManager.getApplication().isUnitTestMode()) { String message = String.format("%1$s is an Eclipse project, but not an Android Eclipse project.\n\n" + "Please select the directory of an Android Eclipse project" + "(which for example will contain\nan AndroidManifest.xml file) and try again.", file.getPath()); Messages.showErrorDialog(message, "Import Project"); } else if (GradleModuleImporter.isGradleProject(target)) { GradleProjectImporter gradleImporter = GradleProjectImporter.getInstance(); gradleImporter.importProject(file); } else { return importWithExtensions(file); } return null; }