Java Code Examples for com.intellij.util.Consumer

The following examples show how to use com.intellij.util.Consumer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: p4ic4idea   Source File: EdtSinkProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
QueueSink(int batchSize, @Nullable ProgressIndicator progress, Runnable onEnd,
        Consumer<E> itemConsumer, Consumer<List<E>> batchConsumer,
        Consumer<Throwable> errorConsumer) {
    assert batchSize > 0;
    this.progress = progress;
    this.batchSize = batchSize;
    this.batch = (E[]) new Object[batchSize];
    this.itemConsumer = itemConsumer;
    this.batchConsumer = batchConsumer;
    this.errorConsumer = errorConsumer;
    this.onEnd = onEnd;

    batchPos = 0;
    itemCount = new AtomicInteger(0);
}
 
Example 2
Source Project: silex-idea-plugin   Source File: ContainerStatusBarWidget.java    License: MIT License 6 votes vote down vote up
@Nullable
@Override
public Consumer<MouseEvent> getClickConsumer() {
    return new Consumer<MouseEvent>() {
        @Override
        public void consume(MouseEvent mouseEvent) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Pimple Definition File", "json"));
            fileChooser.setCurrentDirectory(new File(project.getBasePath()));

            int returnValue = fileChooser.showOpenDialog(null);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                Configuration.getInstance(project).containerDefinitionFileName = fileChooser.getSelectedFile().getAbsolutePath();
                ProjectComponent.configChanged(project);
            }
        }
    };
}
 
Example 3
@NotNull
private static String loadProjectStructureFromScript(
  @NotNull String scriptPath,
  @NotNull Consumer<String> statusConsumer,
  @Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
  final GeneralCommandLine commandLine = PantsUtil.defaultCommandLine(scriptPath);
  commandLine.setExePath(scriptPath);
  statusConsumer.consume("Executing " + PathUtil.getFileName(scriptPath));
  final ProcessOutput processOutput = PantsUtil.getCmdOutput(commandLine, processAdapter);
  if (processOutput.checkSuccess(LOG)) {
    return processOutput.getStdout();
  }
  else {
    throw new PantsExecutionException("Failed to update the project!", scriptPath, processOutput);
  }
}
 
Example 4
@NotNull
private String loadProjectStructureFromTargets(
  @NotNull Consumer<String> statusConsumer,
  @Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
  final File outputFile = FileUtil.createTempFile("pants_depmap_run", ".out");
  final GeneralCommandLine command = getPantsExportCommand(outputFile, statusConsumer);
  statusConsumer.consume("Resolving dependencies...");
  PantsMetrics.markExportStart();
  final ProcessOutput processOutput = getProcessOutput(command);
  PantsMetrics.markExportEnd();
  if (processOutput.getStdout().contains("no such option")) {
    throw new ExternalSystemException("Pants doesn't have necessary APIs. Please upgrade your pants!");
  }
  if (processOutput.checkSuccess(LOG)) {
    return FileUtil.loadFile(outputFile);
  }
  else {
    throw new PantsExecutionException("Failed to update the project!", command.getCommandLineString("pants"), processOutput);
  }
}
 
Example 5
Source Project: consulo-unity3d   Source File: ShaderReference.java    License: Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
public static void consumeProperties(@Nonnull ShaderLabFile file, @Nonnull Consumer<LookupElement> consumer)
{
	for(ShaderProperty shaderProperty : file.getProperties())
	{
		String name = shaderProperty.getName();
		if(name == null)
		{
			continue;
		}
		LookupElementBuilder builder = LookupElementBuilder.create(name);
		builder = builder.withIcon((Image) AllIcons.Nodes.Property);
		ShaderPropertyType type = shaderProperty.getType();
		if(type != null)
		{
			builder = builder.withTypeText(type.getTargetText(), true);
		}
		consumer.consume(builder);
	}
}
 
Example 6
Source Project: Intellij-Plugin   Source File: FileStub.java    License: Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public FileBasedIndex.InputFilter getInputFilter() {
    return new FileBasedIndex.FileTypeSpecificInputFilter() {
        @Override
        public void registerFileTypesUsedForIndexing(@NotNull Consumer<FileType> consumer) {
            consumer.consume(SpecFileType.INSTANCE);
            consumer.consume(ConceptFileType.INSTANCE);
        }

        @Override
        public boolean acceptInput(@NotNull VirtualFile virtualFile) {
            return virtualFile.getExtension() != null && GaugeUtil.isGaugeFile(virtualFile);
        }
    };
}
 
Example 7
@RequiredReadAction
private static void buildDefaultConstructor(@Nonnull DotNetNamedElement element,
		@Nonnull DotNetGenericExtractor extractor,
		@Nonnull Consumer<PsiElement> consumer)
{
	String name = element.getName();
	if(name == null)
	{
		return;
	}
	CSharpLightConstructorDeclarationBuilder builder = buildDefaultConstructor(element, name);

	CSharpMethodDeclaration delegatedMethod = element.getUserData(CSharpResolveUtil.DELEGATE_METHOD_TYPE);
	if(delegatedMethod != null)
	{
		CSharpLightParameterBuilder parameter = new CSharpLightParameterBuilder(element.getProject());
		parameter = parameter.withName("p");

		CSharpMethodDeclaration extractedMethod = GenericUnwrapTool.extract(delegatedMethod, extractor);
		parameter = parameter.withTypeRef(new CSharpLambdaTypeRef(extractedMethod));
		builder.addParameter(parameter);
	}
	consumer.consume(builder);
}
 
Example 8
Source Project: consulo-csharp   Source File: OperatorsProvider.java    License: Apache License 2.0 6 votes vote down vote up
private static void buildOperatorsForDelegates(Consumer<PsiElement> consumer, Project project, CSharpTypeDeclaration typeDeclaration, DotNetTypeRef selfTypeRef)
{
	for(IElementType elementType : new IElementType[]{
			CSharpTokens.PLUS,
			CSharpTokens.MINUS
	})
	{
		CSharpLightMethodDeclarationBuilder builder = new CSharpLightMethodDeclarationBuilder(project);
		builder.setOperator(elementType);

		builder.withParent(typeDeclaration);

		builder.withReturnType(selfTypeRef);

		for(int i = 0; i < 2; i++)
		{
			CSharpLightParameterBuilder parameterBuilder = new CSharpLightParameterBuilder(project);
			parameterBuilder.withName("p" + i);
			parameterBuilder.withTypeRef(selfTypeRef);
			builder.addParameter(parameterBuilder);
		}

		consumer.consume(builder);
	}
}
 
Example 9
Source Project: consulo-csharp   Source File: MapElementGroupCollectors.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected CSharpElementVisitor createVisitor(@Nonnull final Consumer<CSharpMethodDeclaration> consumer)
{
	return new CSharpElementVisitor()
	{
		@Override
		public void visitMethodDeclaration(CSharpMethodDeclaration declaration)
		{
			if(declaration.isOperator())
			{
				consumer.consume(declaration);
			}
		}
	};
}
 
Example 10
@Nonnull
@Override
protected CSharpElementVisitor createVisitor(@Nonnull final Consumer<CSharpConstructorDeclaration> consumer)
{
	return new CSharpElementVisitor()
	{
		@Override
		public void visitConstructorDeclaration(CSharpConstructorDeclaration declaration)
		{
			if(!declaration.isDeConstructor())
			{
				consumer.consume(declaration);
			}
		}
	};
}
 
Example 11
@Nonnull
@Override
protected CSharpElementVisitor createVisitor(@Nonnull final Consumer<CSharpConstructorDeclaration> consumer)
{
	return new CSharpElementVisitor()
	{
		@Override
		public void visitConstructorDeclaration(CSharpConstructorDeclaration declaration)
		{
			if(declaration.isDeConstructor())
			{
				consumer.consume(declaration);
			}
		}
	};
}
 
Example 12
Source Project: consulo-csharp   Source File: RecursiveCallCollector.java    License: Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
@Override
public void collect(PsiElement psiElement, @Nonnull Consumer<LineMarkerInfo> consumer)
{
	if(psiElement.getNode().getElementType() == CSharpTokens.IDENTIFIER && psiElement.getParent() instanceof CSharpReferenceExpression &&
			psiElement.getParent().getParent() instanceof CSharpMethodCallExpressionImpl)
	{
		PsiElement resolvedElement = ((CSharpReferenceExpression) psiElement.getParent()).resolve();
		if(resolvedElement instanceof CSharpMethodDeclaration)
		{
			CSharpMethodDeclaration methodDeclaration = PsiTreeUtil.getParentOfType(psiElement, CSharpMethodDeclaration.class);
			if(resolvedElement.isEquivalentTo(methodDeclaration))
			{
				LineMarkerInfo<PsiElement> lineMarkerInfo = new LineMarkerInfo<PsiElement>(psiElement, psiElement.getTextRange(), AllIcons.Gutter.RecursiveMethod, Pass.LINE_MARKERS,
						FunctionUtil.constant("Recursive call"), null, GutterIconRenderer.Alignment.CENTER);
				consumer.consume(lineMarkerInfo);
			}
		}
	}
}
 
Example 13
Source Project: intellij-haxe   Source File: HaxeIntroduceTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected void doTest(@Nullable Consumer<HaxeIntroduceOperation> customization, boolean replaceAll, String newname, boolean inPlace) {
  String testName = getTestName(true);
  testName = convertStringFirstLetterToUppercase(testName);
  myFixture.configureByFile(testName + ".hx");
  boolean inplaceEnabled = myFixture.getEditor().getSettings().isVariableInplaceRenameEnabled();
  try {
    myFixture.getEditor().getSettings().setVariableInplaceRenameEnabled(inPlace);
    HaxeIntroduceHandler handler = createHandler();
    final HaxeIntroduceOperation operation =
      new HaxeIntroduceOperation(myFixture.getProject(), myFixture.getEditor(), myFixture.getFile(), newname);
    operation.setReplaceAll(replaceAll);
    if (customization != null) {
      customization.consume(operation);
    }
    handler.performAction(operation);
    myFixture.checkResultByFile(testName + ".after.hx");
  }
  finally {
    myFixture.getEditor().getSettings().setVariableInplaceRenameEnabled(inplaceEnabled);
  }
}
 
Example 14
/**
 * {@inheritDoc}
 */
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    /*
     * at version 1.2 fix a bug: 2017.1 版本无法打开图片问题
     * see https://github.com/fantasticmao/ycy-intellij-plugin/issues/9
     */
    DataManager.getInstance().getDataContextFromFocus()
        .doWhenDone((Consumer<DataContext>) (dataContext -> new OpenImageConsumer().accept(dataContext)))
        .doWhenRejected((Consumer<String>) LOG::error);

    // 使打开图片按钮失效,避免重复点击
    notification.expire();
    LOG.info("notification action has been expired");
}
 
Example 15
/**
 * {@inheritDoc}
 */
@Override
public void remind() {
    DataManager.getInstance().getDataContextFromFocus()
        .doWhenDone((Consumer<DataContext>) (dataContext -> new OpenImageConsumer().accept(dataContext)))
        .doWhenRejected((Consumer<String>) LOG::error);
}
 
Example 16
Source Project: IntelliJDeodorant   Source File: AnonymousFeedbackTask.java    License: MIT License 5 votes vote down vote up
AnonymousFeedbackTask(@Nullable Project project,
                      @NotNull String title,
                      boolean canBeCancelled,
                      ErrorReportInformation errorReportInformation,
                      final Consumer<SubmittedReportInfo> callback) {
    super(project, title, canBeCancelled);

    this.errorReportInformation = errorReportInformation;
    myCallback = callback;
}
 
Example 17
Source Project: leetcode-editor   Source File: ErrorReportHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean submit(@NotNull IdeaLoggingEvent[] events, @Nullable String additionalInfo, @NotNull Component parentComponent, @NotNull Consumer<SubmittedReportInfo> consumer) {
    for (IdeaLoggingEvent event : events) {
        Throwable throwable = event.getThrowable();
        if (event.getData() instanceof AbstractMessage) {
            throwable = ((AbstractMessage) event.getData()).getThrowable();
        }

        SentryUtils.submitErrorReport(throwable, additionalInfo);
    }

    return true;
}
 
Example 18
Source Project: bamboo-soy   Source File: RollbarErrorReportSubmitter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean submit(@NotNull IdeaLoggingEvent[] events, @Nullable String additionalInfo,
    @NotNull Component parentComponent, @NotNull Consumer<SubmittedReportInfo> consumer) {
  log(events, additionalInfo);
  consumer.consume(new SubmittedReportInfo(null, null, NEW_ISSUE));
  Messages.showInfoMessage(parentComponent, DEFAULT_RESPONSE, DEFAULT_RESPONSE_TITLE);
  return true;
}
 
Example 19
/**
 * Handle the given {@link JsonObject} response.
 */
private void processResponse(JsonObject response) {
  final JsonElement eventName = response.get("event");
  if (eventName != null && eventName.isJsonPrimitive()) {
    processNotification(response, eventName);
    return;
  }

  if (response.has("error")) {
    return;
  }

  final JsonObject resultObject = response.getAsJsonObject("result");
  if (resultObject == null) {
    return;
  }

  final JsonPrimitive idJsonPrimitive = (JsonPrimitive)response.get("id");
  if (idJsonPrimitive == null) {
    return;
  }
  final String idString = idJsonPrimitive.getAsString();

  final Consumer<JsonObject> consumer;
  synchronized (responseConsumers) {
    consumer = responseConsumers.remove(idString);
  }
  if (consumer == null) {
    return;
  }

  consumer.consume(resultObject);
}
 
Example 20
@Override
public boolean submit(@NotNull IdeaLoggingEvent[] events, @Nullable String additionalInfo,
                      @NotNull Component parentComponent, @NotNull Consumer<SubmittedReportInfo> consumer) {
    EventBuilder eventBuilder = createEvent(events, additionalInfo);
    sentry.sendEvent(eventBuilder);
    consumer.consume(new SubmittedReportInfo(null, null, NEW_ISSUE));
    Messages.showInfoMessage(parentComponent, DEFAULT_RESPONSE, DEFAULT_RESPONSE_TITLE);
    return true;
}
 
Example 21
Source Project: intellij   Source File: AddSourceToProjectHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Given the workspace targets building a source file, updates the .blazeproject 'directories' and
 * 'targets' sections accordingly.
 */
static void addSourceToProject(
    Project project,
    WorkspacePath workspacePath,
    boolean inProjectDirectories,
    Future<List<TargetInfo>> targetsFuture) {
  EventLoggingService.getInstance()
      .logEvent(AddSourceToProjectHelper.class, "AddSourceToProject");
  List<TargetInfo> targets;
  try {
    targets = targetsFuture.get();
  } catch (InterruptedException | ExecutionException e) {
    return;
  }
  boolean addDirectory = !inProjectDirectories;
  boolean addTarget = !targets.isEmpty();
  if (!addDirectory && !addTarget) {
    return;
  }
  if (targets.size() <= 1) {
    AddSourceToProjectHelper.addSourceAndTargetsToProject(
        project, workspacePath, convertTargets(targets));
    return;
  }
  AddSourceToProjectDialog dialog = new AddSourceToProjectDialog(project, targets);
  dialog
      .showAndGetOk()
      .doWhenDone(
          (Consumer<Boolean>)
              ok -> {
                if (ok) {
                  AddSourceToProjectHelper.addSourceAndTargetsToProject(
                      project, workspacePath, convertTargets(dialog.getSelectedTargets()));
                }
              });
}
 
Example 22
Source Project: p4ic4idea   Source File: EdtSinkProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void consumeOne(E item, boolean runEdtAsync) {
    List<Consumer<E>> consumers;
    synchronized (itemConsumers) {
        consumers = new ArrayList<>(itemConsumers);
    }
    for (Consumer<E> consumer : consumers) {
        runEdt(consumer, item, runEdtAsync);
    }
}
 
Example 23
Source Project: p4ic4idea   Source File: EdtSinkProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void consumeBatch(List<E> items, boolean runEdtAsync) {
    List<Consumer<Collection<E>>> consumers;
    synchronized (batchItemConsumers) {
        consumers = new ArrayList<>(batchItemConsumers);
    }
    for (Consumer<Collection<E>> consumer : consumers) {
        runEdt(consumer, items, runEdtAsync);
    }
}
 
Example 24
Source Project: p4ic4idea   Source File: EdtSinkProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void onError(@NotNull Throwable e, boolean runEdtAsync) {
    List<Consumer<Throwable>> consumers;
    synchronized (errorHandlers) {
        consumers = new ArrayList<>(errorHandlers);
    }
    for (Consumer<Throwable> consumer : consumers) {
        runEdt(consumer, e, runEdtAsync);
    }
}
 
Example 25
@NotNull
public String loadProjectStructure(
  @NotNull Consumer<String> statusConsumer,
  @Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
  if (PantsUtil.isExecutable(getProjectPath())) {
    return loadProjectStructureFromScript(getProjectPath(), statusConsumer, processAdapter);
  }
  else {
    return loadProjectStructureFromTargets(statusConsumer, processAdapter);
  }
}
 
Example 26
Source Project: consulo-unity3d   Source File: UnityPluginFileValidator.java    License: Apache License 2.0 5 votes vote down vote up
private static void modifyModules(Project project, Consumer<ModifiableRootModel> action)
{
	List<ModifiableRootModel> list = new ArrayList<>();
	ReadAction.run(() ->
	{
		Unity3dRootModuleExtension unity3dRootModuleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(project);

		if(unity3dRootModuleExtension == null)
		{
			return;
		}

		ModuleManager moduleManager = ModuleManager.getInstance(project);

		Module[] modules = moduleManager.getModules();
		for(Module module : modules)
		{
			String name = module.getName();
			if(name.startsWith("Assembly") && name.endsWith("Editor"))
			{
				ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
				ModifiableRootModel modifiableModel = moduleRootManager.getModifiableModel();

				action.consume(modifiableModel);

				list.add(modifiableModel);
			}
		}
	});

	WriteCommandAction.runWriteCommandAction(project, () ->
	{
		for(ModifiableRootModel modifiableRootModel : list)
		{
			modifiableRootModel.commit();
		}
	});
}
 
Example 27
@Override
public void evaluate(@Nonnull DotNetStackFrameProxy stackFrameMirror,
		@Nonnull DotNetDebugContext dotNetDebugContext,
		@Nonnull DotNetReferenceExpression dotNetReferenceExpression,
		@Nonnull Set<Object> set,
		@Nonnull Consumer<XNamedValue> consumer)
{
}
 
Example 28
@RequiredReadAction
@Override
public void processCompletion(@Nonnull CompletionParameters completionParameters,
		@Nonnull ProcessingContext processingContext,
		@Nonnull Consumer<LookupElement> completionResultSet,
		@Nonnull CSharpTypeDeclaration typeDeclaration)
{
	Unity3dModuleExtension extension = ModuleUtilCore.getExtension(typeDeclaration, Unity3dModuleExtension.class);
	if(extension == null)
	{
		return;
	}

	for(Map.Entry<String, Map<String, UnityFunctionManager.FunctionInfo>> entry : UnityFunctionManager.getInstance().getFunctionsByType().entrySet())
	{
		String typeName = entry.getKey();

		if(!DotNetInheritUtil.isParent(typeName, typeDeclaration, true))
		{
			continue;
		}

		for(UnityFunctionManager.FunctionInfo functionInfo : entry.getValue().values())
		{
			UnityFunctionManager.FunctionInfo nonParameterListCopy = functionInfo.createNonParameterListCopy();
			if(nonParameterListCopy != null)
			{
				completionResultSet.consume(buildLookupItem(nonParameterListCopy, typeDeclaration));
			}

			completionResultSet.consume(buildLookupItem(functionInfo, typeDeclaration));
		}
	}
}
 
Example 29
Source Project: consulo-csharp   Source File: OperatorsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void processAdditionalMembers(@Nonnull DotNetElement element, @Nonnull DotNetGenericExtractor extractor, @Nonnull Consumer<PsiElement> consumer)
{
	if(element instanceof CSharpTypeDeclaration)
	{
		Project project = element.getProject();
		GlobalSearchScope resolveScope = element.getResolveScope();

		CSharpTypeDeclaration typeDeclaration = (CSharpTypeDeclaration) element;

		CSharpMethodDeclaration methodDeclaration = typeDeclaration.getUserData(CSharpResolveUtil.DELEGATE_METHOD_TYPE);
		DotNetTypeRef selfTypeRef;
		if(methodDeclaration != null)
		{
			selfTypeRef = new CSharpLambdaTypeRef(element, methodDeclaration, extractor);
		}
		else
		{
			selfTypeRef = new CSharpTypeRefByTypeDeclaration(typeDeclaration, extractor);
		}

		buildOperators(project, resolveScope, selfTypeRef, element, OperatorStubsLoader.INSTANCE.myTypeOperators.get(typeDeclaration.getVmQName()), consumer);

		if(typeDeclaration.isEnum())
		{
			buildOperators(project, resolveScope, selfTypeRef, element, OperatorStubsLoader.INSTANCE.myEnumOperators, consumer);
		}

		if(DotNetTypes.System.Nullable$1.equals(typeDeclaration.getVmQName()))
		{
			buildNullableOperators(project, resolveScope, selfTypeRef, typeDeclaration, extractor, consumer);
		}

		if(methodDeclaration != null)
		{
			buildOperatorsForDelegates(consumer, project, typeDeclaration, selfTypeRef);
		}
	}
}
 
Example 30
Source Project: consulo-csharp   Source File: ConversionMethodsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void processAdditionalMembers(@Nonnull DotNetElement element, @Nonnull DotNetGenericExtractor extractor, @Nonnull Consumer<PsiElement> consumer)
{
	if(element instanceof CSharpTypeDeclaration)
	{
		Project project = element.getProject();
		GlobalSearchScope resolveScope = element.getResolveScope();

		CSharpTypeDeclaration typeDeclaration = (CSharpTypeDeclaration) element;

		CSharpMethodDeclaration methodDeclaration = typeDeclaration.getUserData(CSharpResolveUtil.DELEGATE_METHOD_TYPE);
		DotNetTypeRef selfTypeRef;
		if(methodDeclaration != null)
		{
			selfTypeRef = new CSharpLambdaTypeRef(element, methodDeclaration, extractor);
		}
		else
		{
			selfTypeRef = new CSharpTypeRefByTypeDeclaration(typeDeclaration, extractor);
		}

		buildConversionMethods(project, resolveScope, selfTypeRef, element, OperatorStubsLoader.INSTANCE.myTypeOperators.get(typeDeclaration.getVmQName()), consumer);

		if(typeDeclaration.isEnum())
		{
			buildConversionMethods(project, resolveScope, selfTypeRef, element, OperatorStubsLoader.INSTANCE.myEnumOperators, consumer);
		}

		if(DotNetTypes.System.Nullable$1.equals(typeDeclaration.getVmQName()))
		{
			buildNullableConversionMethods(project, selfTypeRef, resolveScope, typeDeclaration, extractor, consumer);
		}
	}
}